Safely creating temporary files


I was recently scolded by my friend Clay for using $$ to create temporary files. Clay mentioned that I should be using the mktemp(1) command instead of $$, so I started converting all of my scripts to mktemp (if it’s available). The following block of code provides an example of how mktemp can be used in a shell script:

TMPFILE=`/bin/mktemp -p /var/tmp tmp.file.XXXXX`

if [ -f $TMPFILE ] ;then
    echo "Accessing $TMPFILE"
    echo "program output" >> $TMPFILE
    else
    echo "yikes!"
    exit 1
fi

rm $TMPFILE

$ ./foo

Accessing /var/tmp/tmp.file.Lvyde

This is kinda swell!

This article was posted by Matty on 2006-01-05 01:48:00 -0400 -0400