mktemp manages the creation of temporary files and directories. Synopsis:
mktemp [option]... [template]
Safely create a temporary file or directory based on template, and print its name. If given, template must include at least three consecutive ‘X’s in the last component. If omitted, the template ‘tmp.XXXXXXXXXX’ is used, and option --tmpdir is implied. The final run of ‘X’s in the template will be replaced by alpha-numeric characters; thus, on a case-sensitive file system, and with a template including a run of n instances of ‘X’, there are ‘62**n’ potential file names.
Older scripts used to create temporary files by simply joining the name of the program with the process id (‘$$’) as a suffix. However, that naming scheme is easily predictable, and suffers from a race condition where the attacker can create an appropriately named symbolic link, such that when the script then opens a handle to what it thought was an unused file, it is instead modifying an existing file. Using the same scheme to create a directory is slightly safer, since the mkdir will fail if the target already exists, but it is still inferior because it allows for denial of service attacks. Therefore, modern scripts should use the mktemp command to guarantee that the generated name will be unpredictable, and that knowledge of the temporary file name implies that the file was created by the current script and cannot be modified by other users.
When creating a file, the resulting file has read and write permissions for the current user, but no permissions for the group or others; these permissions are reduced if the current umask is more restrictive.
Here are some examples (although note that if you repeat them, you will most likely get different file names):
$ mktemp file.XXXX
file.H47c
$ mktemp --suffix=.txt file-XXXX
file-H08W.txt
$ mktemp file-XXXX-XXXX.txt
file-XXXX-eI9L.txt
$ dir=$(mktemp -p "${TMPDIR:-.}" -d dir-XXXX) || exit 1
$ fifo=$dir/fifo
$ mkfifo "$fifo" || { rmdir "$dir"; exit 1; }
$ file=$(mktemp -q) && {
> # Safe to use $file only within this block. Use quotes,
> # since $TMPDIR, and thus $file, may contain whitespace.
> echo ... > "$file"
> rm "$file"
> }
$ mktemp -u XXX
Gb9
$ mktemp -u XXX
nzC
The program accepts the following options. Also see Common options.
0 if the file was created,
1 otherwise.