我有一系列需要执行的命令。然而,每当出现“command is not found”错误时,我都需要退出。因此,执行后检查输出不是一个选项。
当“command is not found”和成功时,“$?”变量等于零。
如果需要从脚本中完成这项任务,自然要使用条件语句来表达这种行为:
asdf 2> /dev/null || exit 1
ls /this/file/does/not/exist 2>/dev/null
怎么样? ls 命令仍然存在。 - anishsane[ -x "$executable" ] && echo "Command '$executable' not found" >&2 && exit 1
type
检查其路径。type type
type ls
type xls
输出:
type is a shell builtin
ls is /usr/bin/ls
./test.sh: line 13: type: xls: not found
如果未找到实用程序,则测试返回1。
所以如果 $executable
可以是任何东西(bash内置、别名、二进制文件等),则可以使用以下代码:
type -p ls>/dev/null && ls -l
type -p xls>/dev/null && xls --some_arg
ls
(任何可执行文件),但不会运行xls。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
输出:
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
$executable
是您要查找的可执行文件的路径时,此方法才有效。-x
不会执行路径查找。 - chepnertype
来完成。 - TrueY$?
的值是 127,那么就可以检测到发生了“命令未找到”错误。可以使用 $_
来打印未找到的实用程序名称。 - TrueYjq
为例:jq --version || echo "Please install [jq](https://stedolan.github.io/jq/download) first." && exit 1