2017-03-17 59 views
1

有没有办法更改Bash系统错误消息模板,以便除了原始消息之外还可以打印某些内容?例如:在Bash中自定义“command not found”消息

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

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

取决于您的设置。对于我来说(Ubuntu 16.04),'/ usr/lib/command-not-found'有一个Python脚本,用于打印您可以编辑的消息。它是从'/ etc/bash.bashrc'中声明的函数调用的,它来自'/ etc/profile'。 –

+0

如果你打开'set -x'并发出一个不存在的命令,你可以检查函数在哪里。 –

+0

有没有办法'撤销'set -x命令?为其他类型的错误消息添加消息也不错。 –

回答

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

3

由于猛砸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: [email protected]" 
} 

.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的(CommandNotFound)基本上查找该被命名为喜欢未知的命令包,或​​声音类似Python脚本:

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