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?
Asked
Active
Viewed 1,007 times
2
Anthon
- 78,313
- 42
- 165
- 222
Tobias Kienzler
- 9,184
- 13
- 65
- 106
1 Answers
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!
Tobias Kienzler
- 9,184
- 13
- 65
- 106
-
@Gilles It's a bit sneaky to edit in a [tag: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 07:49