Executing commands when the shell exits


While pruning some cruft from my .profile, I came across several important trap(1) statements that I had defined some time back. If you are unfamiliar with trap(1), this nifty little shell built-in allows the shell to setup signal handlers, which define a series of actions to take if a specific signal is received. The following trap statement will cause the script named ‘~/hi’ to be executed when the user logs out of the shell:

$ trap '~/hi' 0

$ cat hi

echo Howdy!
sleep 60

$ exit

logout
Howdy!
^C

The integer argument to trap(1) indicates the SIGNAL to trap (these are defined in /usr/include/sys/iso/signal_iso.h on Solaris systems), and 0 is a trap(1) constant that will invoke the action when the shell exits.

This article was posted by Matty on 2005-09-26 00:52:00 -0400 -0400