为什么这个带有 evals 的变量扩展会产生不同数量的反斜杠?

Dav*_*son 2 bash

[user@localhost ~]$ declare -p test
declare -- test="eval \\\\\\\\; eval \\\\\\\\;"
[user@localhost ~]$ $test
-bash: \\: command not found
-bash: \: command not found
Run Code Online (Sandbox Code Playgroud)

看起来第二组反斜杠的解析次数是第一组的两倍。我添加任意数量的反斜杠都会发生这种情况。

为什么?

tha*_*guy 6

通过以下方式更容易看到问题echo

$ declare -- test="echo \\\\\\\\; echo \\\\\\\\;"
$ $test
\\\\; echo \\\\;
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它不运行两个echo命令,而是运行一个命令echo并将字符串的其余部分传递给它。发生这种情况是因为$test不会导致 shell 代码进行计算。相反,它会将单词拆分为所谓的简单命令并调用结果。

为了获得您期望的效果,请将其作为 shell 字符串进行计算:

$ eval "$test"
-bash: \: command not found
-bash: \: command not found
Run Code Online (Sandbox Code Playgroud)

要在没有变量的情况下重现结果,其中一个 eval 在解释反斜杠后用 1 调用第二个 eval:

$ 'eval' '\\\\;' 'eval' '\\\\;'
-bash: \\: command not found
-bash: \: command not found

$ eval '\\\\; eval \\\\;'  # Equivalent but more canonical
-bash: \\: command not found
-bash: \: command not found
Run Code Online (Sandbox Code Playgroud)