010-150 · Question #66
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". Bash variable assignment requires no spaces around '=', and any value containing spaces must either be quoted or have each space escaped with a backslash.
Question
Which of the following commands will set the variable text to olaf is home? (Select TWO answers)
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
(33 responses)- A79% (26)
- B12% (4)
- C6% (2)
- D3% (1)
Why each option
Bash variable assignment requires no spaces around '=', and any value containing spaces must either be quoted or have each space escaped with a backslash.
text=olaf\ is\ home uses a backslash before each space to escape it, causing bash to treat the entire string as a single word and assign it to the variable text.
text=$olaf is home causes bash to expand $olaf as a separate variable (likely empty), and the remaining tokens 'is' and 'home' are parsed as a separate command rather than part of the assignment.
$text='olaf is home' is invalid because the dollar sign must not prefix a variable name on the left-hand side of an assignment; bash would attempt to run $text as a command.
text=='olaf is home' uses a double equals sign, which is a string comparison operator used inside [[ ]] conditionals, not a variable assignment operator.
text="olaf is home" wraps the value in double quotes, which preserves literal spaces and most special characters, correctly assigning the full multi-word string to text.
Concept tested: Bash variable assignment with whitespace in values
Source: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameters
Topics
Community Discussion
No community discussion yet for this question.