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?
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
When using BASH, those two lines are 100% equivalent:
variable="$(command)"
variable=$(command)
while these two aren't:
echo $(command)
echo "$(command)"
Alas, the human brain isn't a computer. It's especially not as reliable when it comes to repeat a job.
So chances are that if you mix styles (i.e. you quote when you use command arguments but you don't quote when you assign a variable), that once in a while, you'll get it wrong.
Worse, once in a while you will want the command result to be expanded into individual words. And the next guy who reads your code will wonder if he's looking at a bug.
Conculsion: Since the first two lines are the same, it's easier on the average brain to always quote $()
(even when it's not necessary) to make sure you always quote when you have to.
Testing with so many different commands, it is the same. Can't find a difference.
来源:https://stackoverflow.com/questions/27101227/is-it-necessary-to-quote-command-substitutions-during-variable-assignment-in-bas