在Bash中自定义“未找到命令”消息

时间:2017-03-17 19:18:07

标签: bash

是否有某种程度上改变Bash系统错误消息模板,以便您可以打印除原始消息之外的内容?例如:

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

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

可能是这样的:

curl https://raw.githubusercontent.com/rcaloras/bash-preexec/master/bash-preexec.sh -o ~/.bash-preexec.sh
echo '[[ -f ~/.bash-preexec.sh ]] && source ~/.bash-preexec.sh' >> ~/.bashrc

然后将以下内容添加到.bashrc

preexec() { type "$1" >/dev/null 2>&1 || echo -n 'WTF??? '; }

重新加载你的shell,然后尝试输入一些不存在的命令,比如bububu

$ bububu

将打印

WTF??? -bash: bububu: command not found

重要:阅读https://github.com/rcaloras/bash-preexec