繁体   English   中英

在 bash 中获取上次执行的命令

[英]Get last executed command in 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} =~ .*git\s+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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM