在 bash 脚本中找不到检测命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16918272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
detecting command not found in bash script
提问by GoTTimw
I have a series of command to execute. However I need to exit whenever 'command is not found' error occurs. So post execution check of output is not an option
我有一系列命令要执行。但是,只要发生“找不到命令”错误,我就需要退出。所以输出的执行后检查不是一个选项
The "$?" variable is equal zero when 'command is not found' and on success.
“$?” 当“未找到命令”且成功时,变量为零。
回答by chepner
If the command is not found, the exit status should be 127. However, you may be using bash4 or later and have a function called command_not_found_handledefined. This function is called if a command cannot be found, and it may exit 0, masking the 127 code.
如果未找到该命令,则退出状态应为 127。但是,您可能正在使用bash4 或更高版本,并且已command_not_found_handle定义了一个调用函数。如果找不到命令,则调用此函数,它可能会退出 0,从而屏蔽 127 代码。
Running type command_not_found_handlewill show the definition of the function if it is defined. You can disable it by running unset command_not_found_handle.
如果type command_not_found_handle已定义,运行将显示函数的定义。您可以通过运行禁用它unset command_not_found_handle。
回答by chepner
If this should be done from a script, it's natural to use a conditional to express this kind of behaviour:
如果这应该通过脚本完成,使用条件来表达这种行为是很自然的:
asdf 2> /dev/null || exit 1
回答by TrueY
UPDATED
更新
Try
尝试
[ -x "$executable" ] && echo "Command '$executable' not found" >&2 && exit 1
This will write an error to stderr and exit with 1 exit code.
这会将错误写入 stderr 并以 1 个退出代码退出。
If You have just the name of the utility You can check its path with typebuild-in.
如果您只有实用程序的名称,您可以使用type内置程序检查其路径。
Example:
例子:
type type
type ls
type xls
Output:
输出:
type is a shell builtin
ls is /usr/bin/ls
./test.sh: line 13: type: xls: not found
Test returns 1 if utility not found.
如果未找到实用程序,则测试返回 1。
So if the $executablecan be anything (a bashbuild-in, alias, binary, ...), then this could be used:
因此,如果$executable可以是任何东西(bash内置、别名、二进制文件等),那么可以使用它:
type -p ls>/dev/null && ls -l
type -p xls>/dev/null && xls --some_arg
This will run ls(any executable), but not xls.
这将运行ls(任何可执行文件),但不会运行 xls。
Anyway if in the script the execfailoption is not set (shopt) then the script will exit after stating the bash: some_utility: command not founderror message. If this option is set, then it continues. But You can trapthe pseudo signal ERRand do what You need:
无论如何,如果在脚本execfail中未设置该选项 ( shopt),则脚本将在说明bash: some_utility: command not found错误消息后退出。如果设置了此选项,则它会继续。但是您可以trap使用伪信号ERR并执行您需要的操作:
shopt -s execfail
fnc() { echo $?, $_, Oops;}
trap fnc ERR
ls -d *|head -2
xls
yls
Output:
输出:
a1
a2
./test_tLcn.sh: line 8: xls: command not found
127, xls, Oops
./test_tLcn.sh: line 9: yls: command not found
127, yls, Oops

