I have an error trap as follows:
trap failed ERR function failed { local r=$? set +o errtrace set +o xtrace echo "###############################################" echo "ERROR: Failed to execute" echo "###############################################" # invokes cleanup cleanup exit $r }
There is a part of my code where I do expect an error:
command1 command2 command3 set +e #deactivates error capture command4_which_expects_error set -e #re-activates error capture command5
Overall I need to ignore the trap during the execution of command4_which_expects_error
The set +e does not seem to disable the trap. Any other ways to "untrap" and then "re-trap" ?
The trap command is frequently used to clean up temporary files if the script exits due to interruption. The following example defines the cleanup function, which prints a message, removes all the files added to the $TRASH variable, and exits the script.
The trap keyword catches signals that may happen during execution. You've used one of these signals if you've ever used the kill or killall commands, which call SIGTERM by default. There are many other signals that shells respond to, and you can see most of them with trap -l (as in "list"): $ trap --list.
Here is what you can find in the trap manual:
The KornShell uses an ERR trap that is triggered whenever set -e would cause an exit.
That means it is not triggered by set -e
, but is executed in the same conditions. Adding set -e
to a trap on ERR would make your script exit after executing the trap.
To remove a trap, use:
trap - [signal]
To ignore the failure of a command that you know may fail (but don't necessarily need), you can cause the line to always succeed by appending || true
.
Example:
#!/bin/bash set -e failed() { echo "Trapped Failure" } trap failed ERR echo "Beginning experiment" false || true echo "Proceeding to Normal Exit"
Results
Beginning experiment Proceeding to Normal Exit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With