
我想掛接到未找到指令的處理程序
wim@SDFA100461C:~$ thing
No command 'thing' found, did you mean:
Command 'tping' from package 'lam-runtime' (universe)
Command 'thin' from package 'thin' (universe)
thing: command not found
我想用我自己的腳本覆蓋此行為。
具體來說,我想檢查該命令是否存在於 的輸出中lsvirtualenv -b
,如果存在,我想啟動該 virtualenv。
我該從哪裡開始黑客攻擊?
答案1
對於bash
,其行為由 shell 函數控制command_not_found_handle
(請參閱man bash
COMMAND EXECUTION 下的 )。
要查看函數定義了哪些行為,您可以發出:
declare -p -f command_not_found_handle
您可以透過重新定義函數來變更使用哪個程式command_not_found_handle
。
在 Ubuntu 14.04 LTS 中,預設行為似乎是直接定義在/etc/bash.bashrc
:
# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then
function command_not_found_handle {
# check because c-n-f could've been removed in the meantime
if [ -x /usr/lib/command-not-found ]; then
/usr/lib/command-not-found -- "$1"
return $?
elif [ -x /usr/share/command-not-found/command-not-found ]; then
/usr/share/command-not-found/command-not-found -- "$1"
return $?
else
printf "%s: command not found\n" "$1" >&2
return 127
fi
}
fi
答案2
一般來說
這Linux 雜誌有一篇相當不錯的文章:
來自 bash 的手冊頁:
……只有在雜湊表中找不到該指令時,才會對 PATH 中的目錄執行完整搜尋。如果搜尋不成功,shell 將搜尋名為 command_not_found_handle 的已定義 shell 函數。如果函數存在,則使用原始命令和原始命令的參數作為其參數來呼叫函數,並且該函數的退出狀態將成為 shell 的退出狀態。如果未定義函數,shell 將列印錯誤訊息並返回退出狀態 127。
和
/etc 中的快速 grep 發現了它發生的位置。函數本身位於 /etc/bash_command_not_found 中,而函數透過 /etc/bash.bashrc 包含在您的 bash 會話中(如果存在)。
烏班圖14.04
經驗證據表明,在 Ubuntu 14.04 安裝中,檔案 /etc/bash_command_not_found 不存在,但是,正確的檔案是一個 python 腳本,位於/usr/lib/未找到指令