Reputation: 8304
In Perl, you can write a $SIG{__DIE__}
handler to execute code if the program is exiting with an error. Does bash provide similar functionality?
Here's what I'm trying to do: I have a bash script that creates a new directory and calls several commands which in turn populates the new directory with data files. I'm using set -e
so that the script will terminate immediately if any of the commands fail. In case of a failure, I would like the script to remove the directory that it created. If the script completes successfully, then of course the new output should remain.
Does bash provide a DIE signal handler, or any similar functionality that would enable me to do this?
Upvotes: 1
Views: 261
Reputation: 179392
Since you're using set -e
, you can install an ERR
handler:
trap errfunc ERR
errfunc
will be called if any command exits with a nonzero exit code (and because you are using set -e
, this will terminate the script).
You can pass arguments this way, too:
trap 'errfunc $LINENO' ERR
Since the trap command is eval
'd at the point of the error, this trap will pass the failing command's line number to errfunc
.
Upvotes: 5