blueFast
blueFast

Reputation: 44381

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

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.

Upvotes: 9

Views: 1593

Answers (1)

anubhava
anubhava

Reputation: 785196

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

Upvotes: 7

Related Questions