Run a command on exit in Bash
I was recently trying to track down why a Bash script was exiting prematurely and I discovered a handy little trick to run a piece of code when a Bash script exits for any reason:
function onexit {
echo "`date +'%Y-%m-%d|%H:%M:%S'`|$LOGNAME|$0[$$]|FINISHED" >> /tmp/whatever.log
}
trap onexit EXIT
I was already aware of trap
, but I wasn’t aware of the catch-all EXIT
signal.
Super-handy.