6

How can I trigger a function when a command in bash returns an exit code of 1? I know set -e at the top will just make my code terminate, but I want to call this function first. If the code runs ok I want it to exit normally without the function being called. I don't want to do a $? check after every line. I'm sure there's an easy way to do this but I'm new to bash scripting so I don't know it offhand.

1 Answer 1

4

Set a trap on the ERR pseudosignal:

set -e
error_handler () {
    # do stuff here
}

trap error_handler ERR
Sign up to request clarification or add additional context in comments.

2 Comments

So the ERR pseudosignal is fired any time a 1 exit status is returned from a failed command?
Almost any time. There are a few exceptions that make sense (if the failed command is not the last command in an && or || list, for example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.