用$()替换反引号不起作用


17

我有一些尝试更新的旧脚本。一些代码浓缩为:

 export X=`(echo "abc"; echo "def")`
 echo $X

给出预期的输出:

 abc def

现在互联网告诉我反引号是$()我需要使用的,但是当我尝试时:

export X=$((echo "abc"; echo "def"))

X 没有设置,我得到错误:

bash: echo "abc"; echo "def": syntax error: invalid arithmetic operator (error token is ""abc"; echo "def"")

我究竟做错了什么?

Answers:


27

$(( … ))语法是算术表达式

缺少$(和之间的空格(,以避免算术表达式语法。

实际上,shell命令语言规范中有关命令替换的部分对此进行了警告:

If the command substitution consists of a single subshell, such as:

   $( (command) )

a conforming application shall separate the "`$(`" and '`(`' into two tokens
(that is, separate them with white space). This is required to avoid any
ambiguities with arithmetic expansion.

21
应该注意的是`...`$(...)无论如何都要启动一个子shell,所以(...)不需要内部(浪费一个进程)。例如,您将需要空间$( (...); (...) )(可能需要内部子外壳)。
斯特凡Chazelas

15

尝试 export X="$(echo "abc"; echo "def")"


谢谢,此方法确实有效,但是比其他解决方案需要更多的编辑。
哈罗德2014年

2
+1表示大多数POSIX shell所需的引号(ksh并且bash是唯一的例外)。
斯特凡Chazelas
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.