bash - 如何使用-e检查bash中的错误

标签 bash error-handling

设置-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/

相关文章:

linux - 递归地 chmod for/

bash - 通过 shell 脚本转义字符串中的美元符号

bash - 奇怪的 tput 行为,带有 stderr 重定向

node.js - aws ubuntu上的 Node 错误但不是OSX

bash - 在 Psql 输出中禁用换行

bash - 有没有办法让 bash 作业控制安静?

python - 模糊逻辑: How to detect when a 404 is not actually an error page?

javascript - 如果出现 HTTP 错误 422,如何使用 fetch 获取响应正文?

ruby-on-rails - 验证错误消息散列为空

jsp - 如何在Java ee中冒泡异常?