010-160 · Question #63
Which of the following commands will set the variable text to olaf is home? (Select TWO answers)
The correct answer is A. text=olaf\ is\ home E. text='olaf is home'. Assigning a value containing spaces to a shell variable requires either single quotes or backslash-escaping to prevent word splitting.
Question
Options
- Atext=olaf\ is\ home
- Btext=$olaf is home
- C$text='olaf is home'
- Dtext="olaf is home"
- Etext='olaf is home'
How the community answered
(37 responses)- A86% (32)
- B3% (1)
- C5% (2)
- D5% (2)
Why each option
Assigning a value containing spaces to a shell variable requires either single quotes or backslash-escaping to prevent word splitting.
text=olaf\ is\ home uses backslash escaping before each space, preventing the shell from treating them as word delimiters and correctly assigning the three-word string to text.
text=$olaf is home expands $olaf as a separate variable and leaves 'is home' as an unquoted trailing argument, causing a command-not-found error rather than a clean assignment.
$text='olaf is home' places the dollar sign on the left-hand side of the assignment, which is syntactically invalid; $ is used to dereference a variable's value, not to assign to it.
text="olaf is home" with double quotes does assign the correct string for this specific input, but double quotes permit variable expansion and command substitution, so single quotes are the precise and safer choice for a purely literal string.
text='olaf is home' uses single quotes, which suppress all special-character interpretation including word splitting, making every character including spaces literal and assigning the full string to text.
Concept tested: Shell variable assignment with spaces using quoting
Source: https://www.gnu.org/software/bash/manual/bash.html#Quoting
Topics
Community Discussion
No community discussion yet for this question.