获取 bash 中最后执行的命令

har*_*eep 0 bash prompt built-in

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

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

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

Cha*_*ffy 5

一般情况:收集所有命令

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

store_command() {
  declare -g last_command current_command
  last_command=$current_command
  current_command=$BASH_COMMAND
  return 0
}
trap store_command DEBUG
Run Code Online (Sandbox Code Playgroud)

...然后您可以检查"$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"
}
Run Code Online (Sandbox Code Playgroud)

...可能用于以下内容:

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