bash - 获取 Bash 中上次运行程序的名称

标签 bash

我有一个 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/

相关文章:

node.js - 保持 Node JS 应用程序运行

linux - 如何使用 sed 在 mac 上更改行 (Darwin)

bash - 需要使用 sed 在文本的第二个下划线和第一个连字符之间进行解析

bash - 根据文件输出创建名称/值对

bash - 如何让感叹号在 bash 中被视为双引号中的文字?

bash - 使用 Ansible 创建新用户和密码

linux - 如何在字符串连接中包含破折号(或其他特殊字符)?

linux - 终端和shell脚本中运行命令有什么区别?

linux - 为什么 "which cp | ls -l "不被视为 "ls -l $(which cp)"?

linux - 如何将字符串推送到标准输入?在启动时通过 stdin 提供输入,然后以交互方式读取 stdin 输入