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

Har*_*old 18 bash

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

 export X=`(echo "abc"; echo "def")`
 echo $X
Run Code Online (Sandbox Code Playgroud)

这给出了预期的输出:

 abc def
Run Code Online (Sandbox Code Playgroud)

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

export X=$((echo "abc"; echo "def"))
Run Code Online (Sandbox Code Playgroud)

X 未设置,我收到错误:

bash: echo "abc"; echo "def": syntax error: invalid arithmetic operator (error token is ""abc"; echo "def"")
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Tim*_*imo 28

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

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

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.
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,`\`...\` 和 `$(...)` 无论如何都会启动一个子 shell,所以不需要内部的 `(...)`(浪费一个进程)。例如,您需要在诸如“$( (...); (...) )”之类的东西中使用空间(可能需要内部子外壳)。 (21认同)

JPG*_*JPG 15

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

  • +1 用于包含大多数 POSIX shell 中所需的引号(`ksh` 和 `bash` 是唯一的例外)。 (2认同)