设置-e
后,如何有选择地检查行中是否有错误(并且不会失败)。
我的大多数命令都需要-e
,但不需要。
set -e
foo
bar
biz
if [ ! $? -e 0 ]
echo oh noes
fi
$?
显然不起作用。做这个的最好方式是什么?
最佳答案
在(4.1)bash
手册页中的-e
选项:
The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or ││ list except the command following the final && or ││
biz || echo "oh noes"
仅当
biz
失败时,才会执行||
的RHS,并且保证echo
以状态0退出,因此它不会导致脚本失败。您还可以按照Etan的建议,使用
if
语句运行命令:if ! biz; then
echo "oh noes"
fi
您也可以简单地暂时关闭
-e
:set +e
biz
if [ $? -ne 0 ]; then
echo oh noes
fi
set -e
关于bash - 如何使用-e检查bash中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270228/