Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: how to trap set -e, but not exit

Tags:

bash

exit-code

My scripts have as first instruction:

set -e

So that whenever an error occurs, the script aborts. I would like to trap this situation to show an information message, but I do not want to show that message whenever the script exits; ONLY when set -e triggers the abortion. Is it possible to trap this situation?

This:

set -e

function mytrap {
    echo "Abnormal termination!"
}

trap mytrap EXIT

error

echo "Normal termination"

Is called in any exit (whether an error happens or not), which is not what I want.

like image 429
blueFast Avatar asked Jan 12 '17 17:01

blueFast


People also ask

How do you trap in bash?

To set a trap in Bash, use trap followed by a list of commands you want to be executed, followed by a list of signals to trigger it. For complex actions, you can simplify trap statements with Bash functions.

What does set Pipefail do?

set -o pipefail causes a pipeline (for example, curl -s https://sipb.mit.edu/ | grep foo ) to produce a failure return code if any command errors. Normally, pipelines only return a failure if the last command errors. In combination with set -e , this will make your script exit if any command in a pipeline errors.


1 Answers

Instead of using trap on EXIT, use it on ERR event:

trap mytrap ERR

Full Code:

set -e

function mytrap {
   echo "Abnormal termination!"
}

trap mytrap ERR

(($#)) && error

echo "Normal termination"

Now run it for error generation:

bash sete.sh 123
sete.sh: line 9: error: command not found
Abnormal termination!

And here is normal exit:

bash sete.sh
Normal termination
like image 144
anubhava Avatar answered Oct 21 '22 12:10

anubhava