Is it necessary to quote command substitutions during variable assignment in bash?

bash, sh, shell

Solution

The shell does not perform word splitting for variable assignments (it is standardized that way by POSIX and you can rely on it). Thus you do not need double quotes (but you can use them without making the result different) in

variable=$(command)   # same as variable="$(command)"

However, word-splitting is performed before executing commands, so in

echo $(command)
echo "$(command)"

the result may be different. The latter keeps all multi-space sequences, while the former makes each word a different argument to echo. It is up to you to decide which is the desired behavior.

Interesting shell quirk: there is one more place where quoting a substitution or not makes no difference, namely the expression in a `case expr in` construct.

case $FOO in
  (frob) ...;;
esac

is indistinguishable from

case "$FOO" in
  (frob) ...;;
esac

Problem

Nearly everywhere I've read, including Google's bash scripting style guide mention to necessity of quoting command substitutions (except when specifically desired of course). I understand the when/where/why of quoting command substitutions during general use. For example: `echo "$(cat <<< "* useless string *")"` rather than `echo $(...)` However for variable assignments specifically, I have seen so many examples as such: `variable="$(command)"` Yet I have found no instances where `variable=$(command)` is not equivalent. `variable="$(echo "*")"` and `variable=$(echo "*")` both set the value to '*'. Can anyone give any situations where leaving the substitution unquoted during variable assigment would actually cause a problem?

Original source