返回在 shell-script 中执行的最后一个命令

Hed*_*dge 6 bash shell-script

在 bash 脚本中,我想检索执行的最后一个命令。在 bash 本身中,以下命令就像一个魅力。

lastCommand=$(echo `history |tail -n2 |head -n1` | sed 's/[0-9]* //')
Run Code Online (Sandbox Code Playgroud)

然而,在脚本内部,历史根本不起作用。

有没有办法在脚本中检索命令?

rus*_*ush 5

对于 bash v4+ :

在 shell 中使用交互模式。

设置she-bang为

#!/bin/bash -i
Run Code Online (Sandbox Code Playgroud)

并且history您的脚本内部将起作用。

 $ cat test.sh
#!/bin/bash
history | wc -l
 $ ./test.sh
0
 $ sed -i '1s/bash/bash -i/' test.sh
 $ ./test.sh
6495
Run Code Online (Sandbox Code Playgroud)

在脚本内执行的命令不会记录到历史记录中。

对于 bash v3(可能适用于较旧的)

  • 上述方法不适用于此版本的 bash。但是,您可以完全删除she-bang,并且历史记录将运行良好。这种方式也适用于 bash v4。

  • 将she-bang设置为交互式,不要忘记set -o history像chepner提到的那样。

#!/bin/bash -i
set -o history
Run Code Online (Sandbox Code Playgroud)

附注。history |tail -n2 |head -n1不等于最后一个命令。它是最后一个之前的命令。

请注意,如果 last 或 prelast 命令是多行的,则不会返回正确的结果。

顺便说一句,在控制台中,您可以!-2用来引用 prelast 命令而不是您奇怪的构造。不幸的是,即使在交互模式下,它似乎也不适用于 shell 脚本。