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

标签 bash

有什么办法可以改变 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/

相关文章:

linux - 如何从 shell 脚本向程序发送命令行参数和标准输入

c++ - 创建写入终端的附加文件描述符

mysql - 在 bash 脚本中通过 ssh 创建 mySQL 数据库

linux - 使用 Bash 将所有文件键替换为新值

linux - 在文件列表上运行命令

bash - 通过键盘输入暂停脚本

用 c 编写 bash : don't understand how to implement the pipes

bash - 函数 bash 调用中的引号问题

linux - Bash if 语句 : Can I do an assignment and comparison?

linux - 相当于 Bash 中的 select() 系统调用