In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:
This gives the expected value in all the examples given. Always quote variable references!
When a variable is unquoted, it will:
Undergo field splitting where the value is split into multiple words on whitespace (by default):
/* Foobar is free software */
Each of these words will undergo pathname expansion, where patterns are expanded into matching files:
Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving
/bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/
instead of the variable’s value.
When the variable is quoted it will:
- Be substituted for its value.
- There is no step 2.
This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.