Cleanup Temp Files Shell Pattern

Often it is necessary to save intermediate results of a shell script in a file. I refer below to a file used for this purpose as a temp file. Creating temp files in the current directory is a bad idea, because the user may not have write permission in the current directory. Creating temp files in /tmp introduces the problem of file name collision, if a fixed file name is used.

In either event, the shell script author should ensure that the temp files are removed when the shell script exits, even if the exit is an abnormal one.

With that in mind, I use the following pattern for dealing with temp files:

 TMPDIR="${TMP:-/tmp}/$$"
 trap 'rm -rf "$TMPDIR"' 0
 trap ' exit ' 1 2 15
 mkdir "$TMPDIR"
The first line defines a (hopefully) unique directory in which to keep temp files. The default is to keep them under the /tmp directory, but that can be overriden by the $TMP environment variable. The next line arranges for the entire directory and its contents to be removed when the shell script exits. The third line arranges for the shell script to exit on signals 1 (hangup), 2 (interrupt), or 15 (terminate). The spaces around the word "exit" are there because some versions of the Korn Shell treat the word exit immediately following the trap command to mean the EXIT trap number.

Finally, the directory is created. Now, the shell script can create tempfiles of the form $TMPDIR/xxxx without worry.


CategoryUnixShellPattern


Contributors: MichaelLindner


EditText of this page (last edited October 3, 2003) or FindPage with title or text search