从 Bash 4.0 开始,如果搜索命令不成功,shell 会搜索名为 command_not_found_handle 的函数。如果它不存在,Bash 会打印这样的消息并以状态 127 退出:
$ foo
-bash: foo: command not found
$ echo $?
127
如果它确实存在,它会以命令及其参数作为参数调用,所以如果你有类似的东西
command_not_found_handle () {
echo "It's my handle!"
echo "Arguments: $@"
}
在您的.bashrc 中,Bash 会做出如下反应:
$ foo bar
It's my handle!
Arguments: foo bar
不过,大多数系统都有更复杂的东西。例如,我的 Ubuntu 在/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
这来自/etc/profile。 /usr/lib/command-not-found 是一个 Python 脚本,它使用更多的 Python (CommandNotFound) 来查找名称类似于未知命令或听起来相似的包:
$ sl
The program 'sl' is currently not installed. You can install it by typing:
sudo apt install sl
$ sedd
No command 'sedd' found, did you mean:
Command 'sed' from package 'sed' (main)
Command 'seedd' from package 'bit-babbler' (universe)
Command 'send' from package 'nmh' (universe)
Command 'send' from package 'mailutils-mh' (universe)
sedd: command not found
所以如果你想要简单的定制,你可以提供自己的command_not_found_handle,如果你想定制现有的系统,你可以修改Python脚本。
但是,如上所述,这需要 Bash 4.0 或更高版本。