mktemp [-d] [-q] [-t prefix] [-u] templateXXXXX …
mktemp [-d] [-q] [-u] -t prefix
Creates unique files by taking each of the templates overwriting
trailing Xs with the current process number and/or a
unique letter combination.
Files are created with mode 0600 (unless -u is given) and the filename is output to standard output.
The number of unique file names mktemp can return depends on the number of Xs provided; six
Xs will result in mktemp selecting 1 of 56,800,235,584 (62 ** 6) possible file names.
templates without Xs are not changed
Care should be taken to ensure that it is appropriate to use an environment variable potentially supplied by the user.
Multimple temporary files may be created in a single invocation with differing suffixes,
including one based on the internal template resulting from -t .
Traditionally, scripts take the name of the program with the pid as a suffix and use that as a temporary file name.
This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.
A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a
temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.
-d |
tempfoo=`basename $0`
TMPFILE=`mktemp /tmp/${tempfoo}.XXXXXX` || exit 1
echo "program output" >> $TMPFILE
To allow the use of $TMPDIR:
tempfoo=`basename $0`
TMPFILE=`mktemp -t ${tempfoo}` || exit 1
echo "program output" >> $TMPFILE
The script to catch the error .
tempfoo=`basename $0`
TMPFILE=`mktemp -q /tmp/${tempfoo}.XXXXXX`
if [ $? -ne 0 ]; then
echo "$0: Can't create temp file, exiting..."
exit 1
fi