取得導致 ERR 和 trap 的完整命令列

取得導致 ERR 和 trap 的完整命令列

如何使 trap 回傳導致 ERR 的指令?

$function err_handler() { echo "$0 caused the error"; }

$ trap err_handler ERR

$ grep -ci "failed" test4 &>/dev/null
-bash caused the error

我想要的輸出像

grep caused the error

並且可能(足夠貪婪)擁有整個替換的命令行。有可能嗎(沒有任何黑客手段)?

編輯:我很抱歉沒有提及我的 shell 是 KSH。

答案1

確保命令歷史記錄已啟用(非互動式 shell 預設為關閉)並使用:

#!/bin/bash
set -o history
function trapper () {
    printf "culprit: "
    history 1
}

trap trapper ERR

# your errors go here

答案2

如果您使用的是 Bash,則可以使用下列$BASH_COMMAND參數:

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_COMMAND僅提供複合命令中失敗的命令,而不是整個命令列。

$ function err_handler { echo "error: $BASH_COMMAND" }
$ trap err_handler ERR
$ true blah blah blah && false herp derp
error: false herp derp

第二,管道僅在最後一個命令失敗時才會失敗。如果中間命令失敗但最後一個命令成功,它仍然會成功:

$ echo okay | false herp derp | true lol
# err_handler not called, the last command returned true.

三、$BASH_COMMAND給你未解析的命令列,因此在特殊情況下命令列中的第一個不一定是命令的名稱:

$ false herp derp                       # This is okay.
error: false herp derp
$ {false,herp,derp}                     # An obfuscated way to write `false blah blah`
error: {false,herp,derp}
$ cmd=false
$ $cmd herp derp                        
error: $cmd herp derp

相關內容