![当使用 errexit (-e) 运行时,我如何期望非零返回代码,否则会失败?](https://linux22.com/image/152932/%E5%BD%93%E4%BD%BF%E7%94%A8%20errexit%20(-e)%20%E8%BF%90%E8%A1%8C%E6%97%B6%EF%BC%8C%E6%88%91%E5%A6%82%E4%BD%95%E6%9C%9F%E6%9C%9B%E9%9D%9E%E9%9B%B6%E8%BF%94%E5%9B%9E%E4%BB%A3%E7%A0%81%EF%BC%8C%E5%90%A6%E5%88%99%E4%BC%9A%E5%A4%B1%E8%B4%A5%EF%BC%9F.png)
启用 errexit 选项后,任何失败的命令都将导致脚本退出。我想针对某些预计会失败的命令反转此行为。那就是:我想继续除非指示的命令失败。
我目前正在做这样的事情,它很丑陋:
some_test() {
# retuns nonzero if some condition is met, and zero otherwise
}
some_change() {
# makes a change that should alter the return code of the above test
}
set -e
some_test
echo "expected success, found it"
some_change
set +e
some_test # expect failure
if [[ $? -eq 0 ]]
then
echo "expected failure, found success"
exit(1)
else
echo "expected failure, found it"
fi
set -e
# ...more testing below
我正在寻找更简洁的东西。我知道我可以容忍像这样的失败命令:
some_test
some_change
some_test && true
但我不想仅仅容忍失败,我想断言失败。如果第二个测试通过,我希望我的脚本失败。
答案1
if my_command; then false; else true; fi
我不相信可以用条件体操来模拟这一点。