2

Similarly to set -e performs an exit on "uncaught" $? != 0, I'd like to have this event trigger the execution of another command, e.g. a logger call. How can this be done?

1 Answer 1

3

As hinted at in this question, the answer is setting up a trap on the ERR signal - basically set -e corresponds to trap 'exit' ERR. So to e.g. log errors but continue execution, use

trap 'logger -t myscriptname "Command $BASH_COMMAND exited with code $?"' ERR

In bash, the variable $BASH_COMMAND contains the offending command. $? contains the exit code of the last command executed - note that if you want to perform multiple actions, e.g. logger ...; echo $? the $? will contain logger's exit code, not $BASH_COMMAND's one, so you may have to store it in a variable first, e.g.

trap 'EXITCODE=$?; logger -t "Command $BASH_COMMAND exited with code $EXITCODE"; echo "$BASH_COMMAND at line $LINENO exited with code $EXITCODE"' ERR

Of course you might be better off declaring a function and passing it the $? and $BASH_COMMAND instead of such a long line!

1
  • @Gilles It's a bit sneaky to edit in a ksh into the question to require this edit :P But while you're at it, is there a similar variable in ksh and are there other important differences? Commented Nov 15, 2013 at 7:49

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.