mktemp -- make temporary file name (unique)

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 Make a directory instead of a file.
-q Quietly fail if an error occurs. This is useful if a script does not want error output to go to standard error.
-t prefix Generate a template (using the supplied prefix and TMPDIR if set) to create a filename template.
Default location if TMPDIR is not set is /tmp.

Example on Mac OS X

> echo $TMPDIR
> mktemp -t zz.X

on Linux:

>  echo $TMPDIR

> set |g TMP
> mktemp -t zz.X

-u Operate in unsafe mode. The temp file will be unlinked before mktemp exits.
This is slightly better than mktemp(3) but still introduces a race condition. Use of this option is not encouraged.


Use of mktemp where the script should quit if it cannot get a safe temporary file.
          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


mkdtemp, mkstemp, mktemp(3), environ