歡迎您光臨本站 註冊首頁

Linux神奇的命令行:找不到命令(command not found)

←手機掃碼閱讀     火星人 @ 2014-03-23 , reply:0

最近我從 Ubuntu Edgy 升級到 Ubuntu Feisty,發現 Feisty 一個有趣的程序 command-not-found。當你輸入系統中不存在的命令時,該程序就會提示包含該命令的安裝包並提示用 apt-get 安裝。

以未安裝的命令 trafshow 為例,輸出為:
The program 'trafshow' is currently not installed. You can install it by typing:
sudo apt-get install netdiag
Make sure you have the 'universe' component enabled
bash: trafshow:找不到命令

如果不行的話,請去掉 /etc/bash.bashrc 中以下語句的註釋:
# if the command-not-found package is installed, use it
if [ -x /usr/bin/command-not-found ]; then
function command_not_found_handle {
/usr/bin/command-not-found $1
return $?
}
fi

command-not-found 命令是能返回提示語句的 Python 腳本。因此只要輸入command-not-found 就會輸出提示語句,不管該命令安裝與否。

command-not-found gedit
The program 'gedit' is currently not installed. You can install it by typing:
sudo apt-get install gedit

我們可以用 command-not-found 查找包含特定命令的安裝包,與可以完成同樣操作的dpkg -S相比,command-not-found查詢更迅速。

還可以在 bash 腳本中使用 command-not-found 命令。看下面這個簡單腳本:

#!/bin/bash
Cmd=`which trafshow`;
if [ -n $Cmd ]
then
command-not-found trafshow
fi

以上腳本查找 trafshow 的絕對路徑,如果 tarfshow 沒有安裝,變數 Cmd 是個空值(null)就會返回 command-not-found 的提示語句。這樣做的原因是在 bash 腳本中不會自動使用 command-not-found 特性。我的意思是在 bash 腳本中使用未安裝的命令,不會輸出 command-not-found 的提示語句。

我不知道除了 Ubuntu Feisty 在別的發行版本中是否有 command-not-found,從Agile Testing那裡知道可以在 Ubuntu Edgy中用 apt-get 安裝 command-not-found。

command-not-found 特性會減慢命令行的處理,因為每次輸入未安裝的命令時就會執行查找工作。Niath對 command-not-found 執行時間進行測試,結果是我們能接受的。

[火星人 ] Linux神奇的命令行:找不到命令(command not found)已經有3255次圍觀

http://coctec.com/docs/linux/show-post-119758.html