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

不想你离开。 提交于 2019-11-29 02:28:14

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!