$(...)和`...`之间有什么区别

时间:2021-08-23 15:49:28

The question is as simple as stated in the title: What's the difference between the following two expressions?

问题很简单,如标题所述:以下两个表达式之间的区别是什么?

$(...)
`...`

For example, are the two variables test1 and test2 different?

例如,test1和test2这两个变量是不同的?

test1=$(ls)
test2=`ls`

3 个解决方案

#1


The result is the same, but the newer $() syntax is far clearer and easier to read. At least doubly so when trying to nest. Nesting is not easy with the old syntax, but works fine with the new.

结果是一样的,但更新的$()语法更清晰,更容易阅读。尝试筑巢时至少加倍。使用旧语法嵌套并不容易,但使用新方法可以正常工作。

Compare:

$ echo $(ls $(pwd))

versus:

$ echo `ls \`pwd\``

You need to escape the embedded backticks, so it's quite a lot more complicated to both type and read.

你需要逃避嵌入式反引号,因此对于类型和读取都要复杂得多。

According to this page, there is at least one minor difference in how they treat embedded double backslashes.

根据这个页面,他们如何处理嵌入式双反斜杠至少有一个细微差别。

#2


You might want to read man bash:

你可能想读man bash:

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or . The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

当使用旧式反引号替换形式时,反斜杠保留其字面含义,除非后跟$,`或者。第一个不带反斜杠的反引号终止命令替换。使用$(命令)表单时,括号之间的所有字符组成命令;没有人特别对待。

That's under the "Command Substitution" section of the manpage.

这是在联机帮助页的“命令替换”部分下。

#3


Using ``` is the historical syntax, POSIX has adopted the now standard ` $(...) syntax. See Section 2.6.3

使用```是历史语法,POSIX采用了现在标准的`$(...)语法。见2.6.3节

#1


The result is the same, but the newer $() syntax is far clearer and easier to read. At least doubly so when trying to nest. Nesting is not easy with the old syntax, but works fine with the new.

结果是一样的,但更新的$()语法更清晰,更容易阅读。尝试筑巢时至少加倍。使用旧语法嵌套并不容易,但使用新方法可以正常工作。

Compare:

$ echo $(ls $(pwd))

versus:

$ echo `ls \`pwd\``

You need to escape the embedded backticks, so it's quite a lot more complicated to both type and read.

你需要逃避嵌入式反引号,因此对于类型和读取都要复杂得多。

According to this page, there is at least one minor difference in how they treat embedded double backslashes.

根据这个页面,他们如何处理嵌入式双反斜杠至少有一个细微差别。

#2


You might want to read man bash:

你可能想读man bash:

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or . The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

当使用旧式反引号替换形式时,反斜杠保留其字面含义,除非后跟$,`或者。第一个不带反斜杠的反引号终止命令替换。使用$(命令)表单时,括号之间的所有字符组成命令;没有人特别对待。

That's under the "Command Substitution" section of the manpage.

这是在联机帮助页的“命令替换”部分下。

#3


Using ``` is the historical syntax, POSIX has adopted the now standard ` $(...) syntax. See Section 2.6.3

使用```是历史语法,POSIX采用了现在标准的`$(...)语法。见2.6.3节