我需要知道在與 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 的命令。
uj5u.com熱心網友回復:
一般情況:收集所有命令
您可以使用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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323956.html
