我試圖用zsh在TRAPZERR
函數中觸發某些內容。我需要找到尚未找到的命令,但找不到獲取它的方法。這是我第一次寫的zsh很抱歉,如果很明顯zsh TRAPZERR - 獲取命令運行
TRAPZERR() {
# catch the "not found" commands
if [ $? -eq 127 ]; then
# how to get the command that has been run?
fi
}
我試圖用zsh在TRAPZERR
函數中觸發某些內容。我需要找到尚未找到的命令,但找不到獲取它的方法。這是我第一次寫的zsh很抱歉,如果很明顯zsh TRAPZERR - 獲取命令運行
TRAPZERR() {
# catch the "not found" commands
if [ $? -eq 127 ]; then
# how to get the command that has been run?
fi
}
要觸發後未找到命令一個動作,你可以使用特殊command_not_found_handler鉤子函數。這相當於bash
的command_not_found_handle
,但修正了錯字。
請注意,該函數是在子shell上下文中執行的,因此您在此處設置的任何變量都不會被父shell看到。
$ command_not_found_handler() print -ru2 -- $1 was not found
$ asdasd
asdasd was not found
由於@shellter指出,在TRAPZERR
,命令名稱將在$_
發現,但你需要運行,否則任何命令之前將其存儲,它會被覆蓋:
TRAPZERR() {
local cmd=$_ code=$?
if ((code == 127)); then
print -ru2 -- "Most probably, $cmd was not found"
fi
}
但當心:
$ asdasda
zsh: command not found: asdasda
Most probably, asdasda was not found
$ (asdad)
zsh: command not found: asdad
Most probably, asdad was not found
Most probably, was not found
以上,127是asdad
退出狀態也是子shell,因此這兩個消息。
還要注意的是有上下文,其中TRAPZERR
不叫(同那些地方set -e
不會導致shell退出):
$ asasdasd || :
zsh: command not found: asasdasd
所以,兩個原因,你可能想使用command_not_found_handler代替。
zsh支持'$ _'變量。在其他最近執行命令的shell中,但我不確定這是否適用於腳本或cmd行。也。最好做一些像'拼寫錯誤的名字; myRc = $ ?; TRAPZERR $ _ $ myRc'並在函數中使用另一個本地變量而不是'$?'。任何執行的命令都會重置'$?'的值。祝你好運。 – shellter
@shellter $ _只給我]。我沒有跟隨myRc = $?事情,我該怎麼用這個? – romainberger
無法讀取。請使用back-ticks圍繞像上面的「示例代碼」這樣的項目,比如'$ _'。我在說要用一個特殊的變量捕獲任何重要cmd的返回碼,比如'goodCmd; cmd1rc = $ ?; misspelledCmd; cmd2rc = $?'。一天起飛。可以看看S.O.當我晚點回家的時候。祝你好運。 – shellter