0

我的目标:当我输入一些不是有效的 Unix 命令时,它会被提供给一个特殊的函数,而不是显示“找不到命令”消息。

我找到了这篇文章,它让我走到了一半。

trap 'if ! type -t $BASH_COMMAND >/dev/null; then special_function $BASH_COMMAND; fi' DEBUG

这允许我运行我的特殊功能。但是之后仍然出现“找不到命令”错误。

有什么办法可以告诉 Bash 禁止显示该消息?无论是在这个命令中,还是在特殊函数中,都可以。谢谢!

4

2 回答 2

1

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)

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.

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.

EDIT :

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
}
于 2013-04-16T21:11:04.777 回答
1

我唯一能想到的就是重定向stderr。我认为这不是一个很好的解决方案,但可能是一个起点。就像是:

$BASH_COMMAND 3> /tmp/invalid



if [ -f /tmp/invalid ]; then 
  if [ $(grep -c "command not found" /tmp/invalid) -ne 0 ]; 
     special_function $BASH_COMMAND
     rm /tmp/invalid
  fi
fi

看起来有点笨拙,但可以进行一些调整。

于 2013-04-16T13:47:13.967 回答