I am using an ERR trap to catch any error in my bash script and output what happened to log. (similar to this question: Trap, ERR, and echoing the error line ) It works as expected. The only problem is, that at some point in my script an exitcode !=0 is expected to happen. How can I make the trap not trigger in this situation?
Here is some code:
err_report() {
echo "errexit on line $(caller)" | tee -a $LOGFILE 1>&2
}
trap err_report ERR
Then later in the script:
<some command which occasionally will return a non-zero exit code>
if [ $? -eq 0 ]; then
<handle stuff>
fi
Everytime the command returns non-zero my trap is triggered. Can I avoid this only for this part of the code?
I checked this question: Correct behavior of EXIT and ERR traps when using `set -eu` but I am not really getting how to apply it to my case - if at all aplicable.
if
condition? – masgo May 31 '18 at 22:48if ! foo | bar | baz | quux; then stuff; fi
. – DopeGhoti Jun 01 '18 at 15:59set +e
is used? Is the expectation that the script ignores the error and continues to run, but trap ERR is nevertheless triggered? – Sida Zhou Mar 26 '22 at 02:22set +e
is the opposite ofset -e
.set -e
will cause the script to bail on any uncaught error regardless of if atrap
is set.set +e
will allow a script to continue, though atrap
set toERR
should still fire irrespective to how thee
switch is toggled. – DopeGhoti Mar 28 '22 at 14:14