问题描述
我的目标:当我输入一个不是有效的Unix命令的东西时,它会被送入一个特殊函数,而不是显示Command not found信息。
My goal: when I type in something that's not a valid Unix command, it gets fed to a special function instead of displaying the "Command not found" message.
我发现这篇文章
I found this post, which got me halfway there.
trap 'if ! type -t $BASH_COMMAND >/dev/null; then special_function $BASH_COMMAND; fi' DEBUG
这允许我运行我的特殊功能。但是Command not found错误仍然出现在后面。
This allows me to run my special function. However the "Command not found" error still appears afterwards.
有没有办法我可以告诉Bash抑制该消息?无论是在这个命令中,还是在特殊函数内,都会很好。谢谢!
Is there any way I can tell Bash to suppress that message? Either in this command, or inside the special function, would be fine. Thanks!
推荐答案
这可以通过添加到.zshrc
In ZSH; this can be achieved by adding this to the .zshrc
setopt debugbeforecmd
trap 'if ! whence -w "$ZSH_DEBUG_CMD" >& /dev/null; then special_function $ZSH_DEBUG_COMMAND;fi' DEBUG
exec 2> >(grep -v "command not found" > /dev/stderr)
在一个非常奇怪的方式在bash;因为bash发送提示到stderr(实际上,你将能够看到提示和任何你输入只有在按Enter键后)。另一方面,ZSH将提示符和stderr作为单独的流处理。
This will behave in a very weird way in bash; because bash sends the prompt to stderr ( In effect you will be able to see the prompt and anything you type only after pressing the Enter key ). ZSH on the other hand, handles the prompt and stderr as separate streams.
如果你能找到一种方法使bash发送提示到其他位置dev / tty)类似的东西也会在bash中工作。
If you can find a way to make bash to send the prompt to some other location ( say /dev/tty ) something similar will work in bash also.
编辑:
看来bash版本> 4有 command_notfound_handle
函数,可以做你想要的。您可以在您的〜/ .bashrc
It seems that bash versions > 4 have a command_notfound_handle
function that can do what you want. You can define it in your ~/.bashrc
command_notfound_handle {
special_function $1
# The command that was not found is passed as the first argument to the fn
}
这篇关于我如何禁止Unix的“未找到命令”输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!