“mktemp” Command Usage Examples in Linux

This tutorial explains Linux “mktemp” command, options and its usage with examples.

mktemp – make temporary file name (unique)

DESCRIPTION

advertisement

The mktemp utility takes the given file name template and overwrites a portion of it to create a file name. This file name is unique and suitable for use by the application. The template may be any file name with at least 6 of `X’ Ns s appended to it, for example /tmp/temp.XXXXXX The trailing `X’ Ns s are replaced with the current process number and/or a unique letter combination. The number of unique file names mktemp can return depends on the number of `X’ Ns s provided; six `X’ Ns s will result in mktemp testing roughly 26 ** 6 combinations.

If mktemp can successfully generate a unique file name, the file is created with mode 0600 (unless the -u flag is given) and the filename is printed to standard output.

SYNOPSIS

mktemp [-d ] [-q ] [-u ] template

OPTIONS

advertisement

-d
Make a directory instead of a file.-q
Fail silently if an error occurs. This is useful if a script does not want error output to go to standard error.-u
Operate in “unsafe” mode. The temp file will be unlinked before mktemp exits. Use of this option is not encouraged.-p
Specify a directory prefix to temporary file

Exit Status

The mktemp utility exits with a value of 0 on success, and 1 on failure.

3. Make a unique temporary directory instead of a file using –d option

$ mktemp –d

4. Using a prefix

By default mktemp will use user’s $TMPDIR. If not defined it will use /tmp. You can 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. In this example the temporary file will be created in /chroot/apache/var/tmp unless the user’s TMPDIR environment variable specifies otherwise: