The mktemp utility takes the given filename
template and overwrites a portion of it to
create a unique filename. The template may be
any filename with at least six ‘Xs’
appended to it, for example
/tmp/tfile.XXXXXXXXXX. If no
template is specified a default of
tmp.XXXXXXXXXX is used and the
-t flag is implied (see below).

The trailing ‘Xs’ are replaced with a
unique digit and letter combination. The name chosen depends both on the
number of ‘Xs’ in the
template and the number of collisions with
pre-existing files. The number of unique filenames
mktemp can return depends on the number of
‘Xs’ provided; ten
‘Xs’ will result in
mktemp testing roughly 26 ** 10 combinations.

If mktemp can successfully generate a unique
filename, the file (or directory) is created with file permissions such that
it is only readable and writable by its owner (unless the
-u flag is given) and the filename is printed to
standard output.

mktemp is provided to allow shell scripts to safely
use temporary files. Traditionally, many shell scripts take the name of the
program with the PID as a suffix and use that as a temporary filename. 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.

Use the specified
directory as a prefix when generating the
temporary filename. The directory will be
overridden by the user's TMPDIR
environment variable if it is set. This option implies the
-t flag (see below).

This can be further simplified if we don't care about the actual name of the
temporary file. In this case the -t flag is
implied.

TMPFILE=`mktemp` || exit 1
echo "program output" >> $TMPFILE

In some cases, it may be desirable to use a default temporary directory other
than /tmp. In this example the temporary file
will be created in /extra/tmp unless the user's
TMPDIR environment variable specifies
otherwise.