【问题标题】:Customize "command not found" message in Bash在 Bash 中自定义“找不到命令”消息
【发布时间】:2017-08-09 11:37:27
【问题描述】:

有没有办法改变 Bash 系统错误消息模板,以便您可以打印除原始消息之外的其他内容?例如:

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

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

【问题讨论】:

  • 取决于您的设置。对我来说(Ubuntu 16.04),/usr/lib/command-not-found 有一个 Python 脚本,可以打印您可以编辑的消息。它是从/etc/bash.bashrc 中声明的函数调用的,该函数源自/etc/profile
  • 如果您打开set -x并发出不存在的命令,您可以检查该功能的位置。
  • 有没有办法“撤消”set -x 命令?也可以为其他类型的错误消息添加消息。
  • set 命令将最后一个命令打印到我认为的控制台。
  • 撤消设置:set +x

标签: bash


【解决方案1】:

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

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      相关资源
      最近更新 更多