2017-06-23 60 views
1

我想运行一些无法找到的命令后自动执行一个预先设置的命令。有没有解决方法?'命令未找到'后shell可以运行一个特定的命令

让我清除我的问题。设置一个命令,当我在shell中输入一些命令并得到“command not found”结果时,这个命令会自动执行。

+0

运行命令_only_ if'command not found'? – zombic

+0

你应该使用'which yourCommand'并检查退出状态'$?'并且放置条件语句。如果你正在做一些脚本。 –

回答

4

随着zsh的,使用功能command_not_found_handler

command_not_found_handler() { 
    echo Oups 
} 

使用bash,使用功能command_not_found_handle

command_not_found_handle() { 
    echo Oups 
} 

使用这个机制,有一个的Archlinux的工具,让你的包含你缺少的命令。该工具称为command_not_found,可在AUR和Github上获得。其他发行版也有类似的应用。

+0

这可能是我想要的,我会在稍后尝试。 –

+0

它的工作原理。但是,'command_not_found_handler'中的命令在子shell中执行,它对当前shell没有影响。 –

+1

你想要做什么? – rools

1

你可以,如果以前的成功使用逻辑and操作链的命令,才执行同样的方式:

command1 && command2 

您可以使用逻辑or运营商有command2运行只有command1失败:

command1 || command2 

但是,这将捕获来自command1的所有错误状态,而不仅仅是not found条件。

0

尝试的命令来实现自己的目标,

cmd1 2>&1 | grep "command not found" > /dev/null && cmd2 

简要说明,

  1. cmd1:在命令可能不会在您的系统
  2. cmd2发现:如果cmd1错误信息是“命令未找到”,执行cmd2