Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to untrap after a trap command

Tags:

bash

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" ?

like image 533
gextra Avatar asked Jul 03 '15 07:07

gextra


People also ask

What does the trap command do?

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.

What does trap mean in bash?

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.


2 Answers

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] 
like image 152
pedroapero Avatar answered Oct 07 '22 03:10

pedroapero


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 
like image 35
ti7 Avatar answered Oct 07 '22 03:10

ti7