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?
Since you’re using
set -e, you can install anERRhandler:errfuncwill be called if any command exits with a nonzero exit code (and because you are usingset -e, this will terminate the script).You can pass arguments this way, too:
Since the trap command is
eval‘d at the point of the error, this trap will pass the failing command’s line number toerrfunc.