1

I have a bash script and would like to add in the ability to trap for both EXIT and ERR conditions. The structure is currently

trap cleanup EXIT

function notify(reason) {}
function build {}
function dbops {}
function deploy {}
function cleanup {}

notify('start') \
&& build \
&& dbops \
&& deploy \
&& notify('finished');

What is the recommended way to add in a trap for an error and (optionally) capture the exit reason, and send that via the notify function? Right now all the cleanup does is delete the lock file on EXIT.

I want to be able to send a notify(reason) message out to slack if the script fails unexpectedly, but not send it on normal EXIT.

Is my execution chaining going to interfere with properly trapping for errors?

1
  • What sort of error conditions are you looking for? Eating a signal, or something not returning 0?
    – thrig
    May 20, 2016 at 23:47

1 Answer 1

2

You cannot catch errors with trap ... ERR in commands that have their exit code tested. In your particular case, from the bash man page:

The ERR trap is not executed if the failed command is ... part of a command executed in a && or || list except the command following the final && ...

Generally speaking, the simplest way to guarantee cleanup of a set of functions is to run them all in a subshell, and however it exits you can still do the cleanup.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .