获取bash中最后执行的命令



我需要知道在与PROMPT_COMMAND对应的函数中设置bash提示符时执行的最后一个命令是什么。我的代码如下

function bash_prompt_command () { 
...
local last_cmd="$(history | tail -n 2 | head -n 1  | tr -s ' ' | cut -d ' ' -f3-)"
[[ ${last_cmd} =~ .*gits+checkout.* ]] && ( ... )
...
}

是否有更快的(bash内置的方式)知道是什么命令调用了PROMPT_COMMAND。我尝试使用BASH_COMMAND,但也没有返回实际调用PROMPT_COMMAND的命令。

一般情况:收集所有命令

您可以使用DEBUG陷阱在运行之前存储每个命令。

store_command() {
declare -g last_command current_command
last_command=$current_command
current_command=$BASH_COMMAND
return 0
}
trap store_command DEBUG

…然后你可以检查"$last_command"


特殊情况:只尝试阴影一个(子)命令

如果您只想更改一个命令的操作方式,您可以对该命令进行影子操作。对于git checkout:

git() {
# if $1 is not checkout, just run real git and pretend we weren't here
[[ $1 = checkout ]] || { command git "$@"; return; }
# if $1 _is_ checkout, run real git and do our own thing
local rc=0
command git "$@" || rc=$?
ran_checkout=1 # ...put the extra code you want to run here...
return "$rc"
}

…可能用于以下语句:

bash_prompt_command() {
if (( ran_checkout )); then
ran_checkout=0
: "do special thing here"
else
: "do other thing here"
fi
}