When should I assign double quotes around variables like
"${var}"to prevent problems caused by spaces?
Implicit in this question is
Why isn’t
${variable_name}good enough?
${variable_name} doesn’t mean what you think it does …
… if you think it has anything to do
with problems caused by spaces or “glob” (filename pattern) characters
(in variable values).
${variable_name} is good for this:
$ bar=foo
$ bard=Shakespeare
$ echo $bard
Shakespeare
$ echo ${bar}d
food
and nothing else! 1
${variable_name} doesn’t do any good
unless you’re immediately following it with a character
that could be part of a variable name:
a letter (A-Z or a-z), an underscore (_), or a digit (0-9).
And even then, you can work around it:
$ echo "$bar"d
food
or
$ fourth_letter=d
$ echo $bar$fourth_letter
food
I’m not trying to discourage its use —
echo "${bar}d" is probably the best solution here —
but to discourage people from relying on braces instead of quotes,
or applying braces instinctively and then asking,
“Now, do I need quotes, also?”
You should always use quotes unless you have a good reason not to,
and you’re sure you know what you’re doing.
_________________
1 Except, of course,
for the fact that the fancier forms of parameter expansion, for example,
${parameter:-[word]},
${parameter%[word]},
${#parameter} and ${parameter^^},
build on the ${parameter} syntax.
Also, you need to use ${10}, ${11}, etc.,
to reference the 10th, 11th, etc., positional parameters —
quotes won’t help you with that.