RSS Feed Share on Twitter

You can now buy this tutorial as a PDF for $5!


Trap is a simple, but very useful utility. If your script creates temporary files, such as this simple script which replaces FOO for BAR in all files in the current directory, /tmp is clean when the script exits. If it gets interrupted partway through, though, there could be a file lying around in /tmp:

trap cleanup 1 2 3 6

  echo "Caught Signal ... cleaning up."
  rm -rf /tmp/temp_*.$$
  echo "Done cleanup ... quitting."
  exit 1

### main script
for i in *
  sed s/FOO/BAR/g $i > /tmp/temp_${i}.$$ && mv /tmp/temp_${i}.$$ $i
The trap statement tells the script to run cleanup() on signals 1, 2, 3 or 6. The most common one (CTRL-C) is signal 2 (SIGINT). This can also be used for quite interesting purposes:

trap 'increment' 2

  echo "Caught SIGINT ..."
  X=`expr ${X} + 500`
  if [ "${X}" -gt "2000" ]
    echo "Okay, I'll quit ..."
    exit 1

### main script
while :
  echo "X=$X"
  X=`expr ${X} + 1`
  sleep 1
The above script is quite fun - it catches a CTRL-C, doesn't exit, but just changes how it's running. How this could be useful for positive and negative effect is left as an exercise to the reader:) This particular example concedes to quit after 4 interrupts (or 2000 seconds). Note that anything will be killed by a kill -9 <PID> without getting the chance to process it.

Here is a table of some of the common interrupts:

00On exit from shell
1SIGHUPClean tidyup
9SIGKILLDie Now (cannot be trapped)
14SIGALRMAlarm Clock

Note that if your script was started in an environment which itself was ignoring signals (for example, under nohup control), the script will also ignore those signals.



You can buy the content of this tutorial as a PDF to download to all of your devices!


You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don't forget to include the simple addition question at the end of the form, to prove that you are a real person!