Shell Script Krusties

October 18th, 2007

If your writing a shell script that writes files, its bad practice not to use trap. Useful scripts get used, copied, and shared. Users love to use Ctrl-C. If I had a nickel for every time I have heard “Ctrl-C out of it” being said by some user who did not understand the implications, I might have a few Euros. As such many, many scripts out there leave “krusties” all over the place.

Take this shell script for example:

$ cat krusties.sh
#!/bin/bash
tmpfile="/tmp/krusty"
cleanup()
{
rm -f $tmpfile
}
touch $tmpfile
sleep 5 # doing something useful here...
cleanup

It assumes that the cleanup function will always run. However, if I run the script and press Ctrl-C while its sleeping…

$ ls -l /tmp/k*
ls: /tmp/k*: No such file or directory
$ ./krusties.sh
^C
$ ls -l /tmp/k*
-rw-rw-r-- 1 brock brock 0 Oct 15 10:41 /tmp/krusty
$ rm -f /tmp/krusty

It leaves a krusty. In the best case scenario this is annoying. In the worst case it can cause serious problems. (E.g., lock files.) Now consider this modified script:

$ cat krusties.sh
#!/bin/bash
tmpfile="/tmp/krusty"
cleanup()
{
rm -f $tmpfile
exit
}
trap "cleanup" SIGINT SIGTERM
touch $tmpfile
sleep 5 # doing something useful here...
cleanup

I added the line trap “cleanup” SIGINT SIGTERM which causes the shell to execute the cleanup function on Ctrl-C and the terminate signal. If not killed, it runs cleanup on exit. This version does not leave the krusty:

$ ls -l /tmp/k*
ls: /tmp/k*: No such file or directory
$ ./krusties.sh
^C
$ ls -l /tmp/k*
ls: /tmp/k*: No such file or directory

3 Responses to “Shell Script Krusties”

  1. Samuel Huckins Says:

    A great tip! I could use this in many of my scripts. Thanks!

  2. gregf Says:

    Liked the tip myself, thanks. Now I have two scripts I should apply it to.

  3. Chris F.A. Johnson Says:

    I use ‘trap cleanup EXIT’, which runs the cleanup function no matter how the shell exits.

Leave a Reply

If Wordpress eats your comment (shell output, loops, ex..) email the text to me.