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?
Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.
There are a few other contexts where the double quotes are optional, but you can't go wrong with the simple rule: always use double quotes around variable and command substitutions unless you want the split+glob operator.
Echoing textThe echo command doesn't require any variety of quote characters much of the time. You can echo a phrase like this without bothering with quotes of any kind.
Command substitution allows you to capture the output of any command as an argument to another command. You can perform command substitution on any command that writes to standard output. The read special command assigns any excess words to the last variable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With