在bash中进行变量分配时是否需要引用命令替换? [英] Is it necessary to quote command substitutions during variable assignment in bash?

查看:70
本文介绍了在bash中进行变量分配时是否需要引用命令替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我读过的几乎所有地方,包括Google的bash脚本风格指南中,都提到了引用命令替换的必要性(当然,除非特别需要).

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).

我了解一般使用期间何时/何地/为何引用命令替换.例如:echo "$(cat <<< "* useless string *")"而不是echo $(...)

I understand the when/where/why of quoting command substitutions during general use. For example: echo "$(cat <<< "* useless string *")" rather than echo $(...)

但是,对于变量分配,我已经看到了很多这样的例子: variable="$(command)"

However for variable assignments specifically, I have seen so many examples as such: variable="$(command)"

但是我没有发现variable=$(command)不等效的情况.

Yet I have found no instances where variable=$(command) is not equivalent.

variable="$(echo "*")"variable=$(echo "*")都将值设置为'*'.

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?

推荐答案

shell不会对变量分配执行分词(POSIX对此进行了标准化,您可以依靠它).因此,您不需要在

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.

有趣的shell怪癖:还有另外一个地方,用引号引起或不引起任何区别,即case expr in构造中的表达式.

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

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

这篇关于在bash中进行变量分配时是否需要引用命令替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆