我有一个 bash 脚本,我在其中使用 trap 命令捕获错误,我希望能够打印最后一条命令(失败的命令)的名称
#!/bin/bash
function error
{
# echo program name
}
trap error ERR
# Some commands ...
/bin/false foo # For testing
我不确定要在 error
函数中放入什么。我试过 echo $_
但这只有在命令没有参数的情况下才有效。我也尝试过 !!
但这给了我“!!: command not found”。在交互式提示符(也是 bash)下,我得到:
$ /bin/false foo
$ !!
/bin/false foo
这似乎正是我想要的。为什么不同? 在脚本中获取上一个命令的名称的最简单方法是什么?
最佳答案
在陷阱函数中尝试 echo $BASH_COMMAND
。
来自 man bash
:
BASH_COMMAND
The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap.
关于bash - 获取 Bash 中上次运行程序的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4197441/