gpt4 book ai didi

bash - 在 Bash 中自定义 "command not found"消息

转载 作者:行者123 更新时间:2023-12-02 17:20:50 26 4
gpt4 key购买 nike

有什么办法可以改变 Bash 系统错误消息模板,以便您可以在原始消息之外打印一些内容吗?例如:

Macbook Air:~/Public]$ lfe
-bash: lfe: WTF command not found

Macbook Air:~/Public]$ lfe
-bash: lfe: #!&**! command not found

最佳答案

自 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 会这样 react :

$ 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 或更高版本。

关于bash - 在 Bash 中自定义 "command not found"消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com