理解 echo 的输出后跟一些感叹号

Dha*_*mit 4 bash echo

我前阵子在玩echo $$。好吧,它显示了 shell 的 pid。但后来我做了echo !,立即显示!。然后echo !!产生

echo echo !
echo !
Run Code Online (Sandbox Code Playgroud)

$echo !!!

echo echo echo !!
echo echo !!
Run Code Online (Sandbox Code Playgroud)

我无法理解输出。据我所知,echo !!给出了在shell上执行的最后一个命令。但是我在这里得到的输出对我来说很奇怪。我使用 bash 外壳。

les*_*ana 12

历史事件标志 !!是由你的历史上最后一个命令替换。Bash 首先打印出将如何执行的命令,然后执行它。

例子:

$ foo
foo: command not found
$ !!
foo                     # command to be executed
foo: command not found  # result of execution
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

$ echo !
!
$ echo !!
echo echo !         # command to be executed
echo !              # result of execution
$ echo !!!
echo echo echo !!   # command to be executed
echo echo !!        # result of execution
Run Code Online (Sandbox Code Playgroud)

请注意,带有事件指示符的命令不会按键入的方式插入到历史记录中。首先事件指示符被展开,然后命令被输入到历史中。这就是为什么在第三个命令 ( echo !!!) 中,事件指示符不是由echo !!(键入的第二个命令)代替,而是由echo echo !(扩展的第二个命令)代替。

这是最后一个命令,替换部分突出显示:

$ echo (!!)!
echo (echo echo !)! # command to be executed
echo echo !!        # result of execution
Run Code Online (Sandbox Code Playgroud)