7.8 Temporary File Management


7.8 Temporary File Management

Sometimes it is necessary to create a temporary file to collect output for use by a later command. When making such a file, you must make sure that the filename is unique enough that no other programs will accidentally write to the temporary file.

You should know how to use the mktemp command to create temporary filenames. Here is a script that shows you what device interrupts have occurred in the last two seconds:

 #!/bin/sh TMPFILE1=`mktemp /tmp/im1.XXXXXX` TMPFILE2=`mktemp /tmp/im2.XXXXXX` cat /proc/interrupts > $TMPFILE1 sleep 2 cat /proc/interrupts > $TMPFILE2 diff $TMPFILE1 $TMPFILE2 rm -f $TMPFILE1 $TMPFILE2 

The argument to mktemp is a template. mktemp converts the XXXXXX to a unique set of characters and creates an empty file with that name (without the XXXXXX , the command fails). Notice that this script uses variable names to store the filenames, so that you only have to change one line if you want to change a filename.

Note  

Not all Unix flavors come with mktemp . If you're having portability problems, you might want use the $$ special variable to construct a temporary filename based on the process ID.

Another problem is that scripts that employ temporary files are vulnerable to signals that abort the script and leave temporary files behind. In the preceding example, pressing CONTROL-C before the second cat command leaves a temporary file in /tmp . You want to avoid this if possible. Use the trap command to create a signal handler to catch the signal that CONTROL-C generates. The handler removes the temporary files:

 #!/bin/sh TMPFILE1=`mktemp /tmp/im1.XXXXXX` TMPFILE2=`mktemp /tmp/im2.XXXXXX` trap "rm -f $TMPFILE1 $TMPFILE2; exit 1" INT  ... 

Notice that you must use exit in the handler to explicitly end script execution. Otherwise, the shell continues running as usual after running the signal handler.




How Linux Works
How Linux Works: What Every Superuser Should Know
ISBN: 1593270356
EAN: 2147483647
Year: 2004
Pages: 189
Authors: Brian Ward

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net