$()周围的报价是否不必要?

时间:2017-01-04 13:23:50

标签: bash

我一直以为我必须在bash周围加上$()的引号,比如:

FOO="$(echo "bar    baz")"

显然这是不必要的变量分配期间至少

$ FOO=$(echo "foo       bar")
$ echo "$FOO"
foo       bar

另一方面,如果我只是尝试为变量分配多个单词,我会收到一个错误,因为它被解释为“后续命令持续时间的设置变量”:

$ FOO=bar     fooooo
fooooo: command not found

此外,如果我只是在非作业上下文中使用$ strong()而不使用引号,则会再次将视为单独的单词

$ echo $(echo "baa    beee")
baa beee

那么,关于$()和“”交互的规则是什么,以及非引用变体的安全性如何?我特别感谢manpage引用或其他一些权威引用。此外,这里有一些“好的做法/风格”吗?

1 个答案:

答案 0 :(得分:4)

简而言之,引用是必要的,以抑制其他正常行为。在大多数情况下,您需要引用命令替换来抑制分词和路径名扩展。

在手册页的"命令替换":

If the [command] substitution appears within double quotes, word 
splitting and pathname expansion are not performed on the results.

但是,作业的右侧不是这些背景之一。从手册页中,在" PARAMETERS":

A variable may be assigned to by a statement of the form

              name=[value]

If  value  is  not  given,  the  variable is assigned the null string.  All values
undergo tilde expansion, parameter and variable expansion, command  substitution,
arithmetic  expansion,  and quote  removal (see EXPANSION below).

请注意,既未提及分词,也未提及路径名扩展。

作为一项规则,如有疑问,请引用任何扩展。您想要分词和扩展的路径名扩展的时间很少,而且通常很明显。