This tutorial explains Linux “mktemp” command, options and its usage with examples.
DESCRIPTION
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
-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.
EXAMPLES
1. Create temporary filename in using a user’s $TMPDIR environment variable
Sample output:
$ mktemp /tmp/tmp.yTfJX35144
You can store filename to a variable:
OUT="$(mktemp)" ls > $OUT
2. Simple Script example which quits if mktemp is unable to create a unique temp file
TMPFILE=`mktemp -q /tmp/$0.XXXXXX` if [ $? -ne 0 ]; then echo "$0: Can't create temp file, exiting..." exit 1 fi
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:
$ mktemp -p /chroot/apache/var/tmp php.lock.XXXXXXXXXX
Sanfoundry Global Education & Learning Series – 1000 Linux Tutorials.
- Buy Information Technology Books
- Apply for Programming Internship
- Buy Linux Books
- Apply for Linux Internship
- Practice Programming MCQs