Skip to main content
added 688 characters in body
Source Link
DopeGhoti
  • 79.2k
  • 10
  • 107
  • 141

An ERR trap will not trigger if an error code is immediately "caught", which means that you can use if statements and whatnot without having to flip error trapping on and off all the time. However, you cannot use checking $? for flow control, because as the time you get to that check, you already (may) have the uncaught error.

If you have a command you expect to fail -- and you do not want those failures to trigger the trap, you simply have to catch the failure. Wrapping them in an if statement is clunky and verbose, but this shorthand works nicely:

/bin/false || :  # will not trigger an ERR trap

However, if you want to do things when a command fails, if will be fine here:

if ! /bin/false; then
    echo "this was not caught by the trap!"
fi

Or alternatively, else will catch the error state also:

if /bin/false; then
    : # dead code
else
    echo "this was not caught by the trap!"
fi

In sum, set -e and trap "command" ERR only get tripped if there is an error condition which is not immediately and intrinsically accounted for.

If you have a command you expect to fail -- and you do not want those failures to trigger the trap, you simply have to catch the failure. Wrapping them in an if statement is clunky and verbose, but this shorthand works nicely:

/bin/false || :  # will not trigger an ERR trap

An ERR trap will not trigger if an error code is immediately "caught", which means that you can use if statements and whatnot without having to flip error trapping on and off all the time. However, you cannot use checking $? for flow control, because as the time you get to that check, you already (may) have the uncaught error.

If you have a command you expect to fail -- and you do not want those failures to trigger the trap, you simply have to catch the failure. Wrapping them in an if statement is clunky and verbose, but this shorthand works nicely:

/bin/false || :  # will not trigger an ERR trap

However, if you want to do things when a command fails, if will be fine here:

if ! /bin/false; then
    echo "this was not caught by the trap!"
fi

Or alternatively, else will catch the error state also:

if /bin/false; then
    : # dead code
else
    echo "this was not caught by the trap!"
fi

In sum, set -e and trap "command" ERR only get tripped if there is an error condition which is not immediately and intrinsically accounted for.

Source Link
DopeGhoti
  • 79.2k
  • 10
  • 107
  • 141

If you have a command you expect to fail -- and you do not want those failures to trigger the trap, you simply have to catch the failure. Wrapping them in an if statement is clunky and verbose, but this shorthand works nicely:

/bin/false || :  # will not trigger an ERR trap