Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 3 down vote accepted

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!

share|improve this answer
@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? – Tobias Kienzler Nov 15 '13 at 7:49

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.