When should I double-quote a parameter expansion? [duplicate]

[*]

Always use "$x", at least at first. The cases where this is correct far outnumber the cases where it may be wrong.

Parameter expansions are subject to both word-splitting and pathname expansion, neither of which you usually want. Quoting the expansion preserves the literal content of the parameter.

Compare

$ x="foo * bar"
$ printf '%s\n' "$x"
foo * bar

to

$ printf '%s\n' $x
foo
<every file in the current directory>
bar

If your logic does require word-splitting or pathname expansion to take place, there is a good chance that your script design needs to be changed to avoid that requirement.

Always quoting parameter expansions will, at the very least, reduce the number of bugs you need to fix.


As a corollary, there is never a reason to use ${foo[@]} unquoted. The very existence of @ indexing is to have special behavior (compared to * indexing) when quoted. When unquoted, the two are identical, so you may as well use ${foo[*]}.

The same argument applies to the special parameters $@ and $*.

$ x=("foo bar" baz)
$ printf '%s\n' "${x[@]}"  # expands to two elements words, one per element
foo bar
baz
$ printf '%s\n' "${x[*]}"  # expands to one word; elements join using IFS
foo bar baz
$ printf '%s\n' ${x[*]}    # expands to three words
foo
bar
baz

Leave a Comment