[TIL] The trap command can capture a shell exit

I came across the trap command from this blog post which I came across while trying to get ssh-agent working with OpenBSD. I didn’t know of this command!

The command has the following syntax: trap <action> <signal>

If you include this in your .profile or .bash_profile for instance it will trigger <action> whenever the shell it is invoked in gets the <signal> signal. The <signal> can be EXIT or 0, or the usual suspects like SIGHUP (1), SIGKILL (9), etc. Check the manpage for a list.

You might be thinking, as I did, why not just use .bash_logout if you are on Bash? Well, for one, .bash_logout is Bash specific; and for another, .bash_logout is not run if you exit the shell by just closing the window for instance. Any <action> specified via trap on the <signal> EXIT, however, is run however you exit the shell. That is super useful. Thus you could add the following to your .bash_profile to ensure that .bash_logout is always run:

The <action> is run as though you did eval <action>. Or you could do more things like the author of this answer goes into …