参见英文答案 >
Bash ignoring error for a particular command6个
我有一个bash脚本,我想全局启用set -e.
我有一个bash脚本,我想全局启用set -e.
但是不是一直禁用它并重新启用它,我想知道是否有一种方法可以选择性地禁用错误处理.
例如,从systemd运行的命令可以在减号之前忽略错误. bash有同等效力吗?
例如
#!/bin/bash set -e WAN_IF=eth2 # Ignore error on next line tc qdisc del dev ${WAN_IF} root # I want errors to stop the script on this line tc qdisc add dev ${WAN_IF} root handle 1: htb default 10 ... etc
由于需要启用/禁用很多,我不想继续执行以下操作:
set +e tc qdisc del dev ${WAN_IF} root # I want errors to stop the script on this line set -e tc qdisc add dev ${WAN_IF} root handle 1: htb default 10 ...
添加|| :(或其他任何保证不会失败,但这是最简单的)到命令的结尾.
原文链接:https://www.f2er.com/bash/384271.html虽然很多人只是告诉你set -e不值得,因为它没有你想象的那么有用(并导致这样的问题),手动错误检查是一个更好的策略.
(我不在那个阵营中,但是我越是遇到这样的问题,我觉得有一天我可能会到达那里.)
从thatotherguy的评论解释set -e的主要问题之一:
The problem with
set -e
isn’t that you have to be careful about which commands you want to allow to fail. The problem is that it doesn’t compose. If someone else reads this post and usessource yourfile || :
to source this script while allowing failure,suddenlyyourfile
will no longer stop on errors anywhere. Not even on failing lines after an explicitset -e
.