Linux mktemp Command: Create Secure Temporary Files and Directories

This guide explains how to create unpredictable temporary files and directories with Linux mktemp, use templates and TMPDIR, clean up with trap, and avoid unsafe dry runs. It focuses on practical Linux usage, predictable automation, and the cases where a seemingly small path or option mistake can change the result.

The examples use GNU Coreutils behavior. Check mktemp --help, man mktemp, and your distribution documentation when portability or a version-specific option matters.

What Is the mktemp Command?

mktemp atomically creates a temporary file or directory with an unpredictable unique name and prints that path. This avoids the predictable-name race conditions common in scripts that combine a program name with a process ID.

Basic Syntax

mktemp [OPTION]... [TEMPLATE]

Quote paths that contain spaces. When supported, place -- before operands that begin with a hyphen so they are not interpreted as options.

Basic mktemp Usage

Create a temporary file

With no template, mktemp uses the system temporary-directory policy, creates the file, and prints its path. Stop if creation fails.

tmp_file=$(mktemp) || exit 1
printf '%s\n' "$tmp_file"

Choose a filename pattern

A template ends with a run of X characters that mktemp replaces. A suffix can be inferred or supplied explicitly.

mktemp report-XXXXXXXX.csv
mktemp --suffix=.log app-XXXXXXXX

Create a temporary directory

Use -d for a private temporary workspace. A stricter umask may further restrict its permissions.

tmp_dir=$(mktemp -d) || exit 1
printf '%s\n' "$tmp_dir"

Checking the Actual Creation Path

mktemp returns the path of the securely created temporary file to standard output. Do not guess the name to create it or rely only on the -u result.

tmpfile=$(mktemp)
printf '%s\n' "$tmpfile"
test -f "$tmpfile"
echo $?

The output is one line with the temporary path and 0. The string of the temporary path differs with each execution. Once the task is complete, make sure to verify that it is the file you actually created and clean up the variable path enclosed in quotes.

Key Options

Option Purpose
-d Create a directory instead of a file.
-p DIR Create from a template relative to the selected directory.
--tmpdir Use TMPDIR or the default temporary directory when no argument is given.
--suffix=SUFFIX Append a suffix without a slash.
-q Suppress diagnostics while preserving failure status.
-u Print an unused name without creating it; unsafe for later secure creation.

Long options often make reviewed scripts easier to understand. When a script must run on non-GNU systems, verify every non-POSIX option on the target platform.

Practical Examples

Clean up a temporary file with trap

Register cleanup immediately after successful creation. Quote every path variable and use -- where supported.

tmp_file=$(mktemp) || exit 1
trap 'rm -f -- "$tmp_file"' EXIT HUP INT TERM

printf '%s\n' 'temporary data' > "$tmp_file"

Use a temporary work directory

When several intermediate files are needed, create one private directory and use fixed names only inside that directory.

work_dir=$(mktemp -d) || exit 1
trap 'rm -rf -- "$work_dir"' EXIT HUP INT TERM

input=$work_dir/input
output=$work_dir/output

Select the parent directory

Use -p when temporary data must reside on a particular filesystem. The parent directory must already exist and have suitable permissions.

mkdir -p "$HOME/.cache/myapp"
cache_file=$(mktemp -p "$HOME/.cache/myapp" cache-XXXXXXXX) || exit 1

mktemp and Related Commands

Command or method Primary role Best fit
mktemp Create a unique name and object atomically Secure temporary files and directories
touch Create a chosen fixed filename Ordinary files without shared-name races
mkdir Create a chosen directory name Permanent or predetermined paths
mktemp -u Print a currently unused name only Not suitable for secure later creation

Important Cautions

Do not create a file later from mktemp -u output

Another process can claim the name between selection and use. Let mktemp create the object itself.

Quote cleanup variables

An empty or split path can make a cleanup command target the wrong place. Verify creation and quote the variable every time.

Know where sensitive temporary data is stored

The temporary directory may be disk-backed, swapped, snapshotted, or backed up. Apply a separate data-handling policy for secrets.

FAQ

Why is mktemp safer than adding a process ID to a name?

It chooses an unpredictable name and creates the object atomically, reducing name-squatting and symlink races.

How do I create a temporary directory?

Use mktemp -d and store its printed path in a quoted variable.

Are temporary files removed automatically?

Usually no. Register cleanup with trap in a shell script.

When is TMPDIR used?

It can select the parent used by the default template or --tmpdir. Check the installed version for exact behavior.

Related Resources

More in This Category
Linux zip Command: Create ZIP Archives

Linux zip Command: Create ZIP Archives

Learn how to create ZIP Archives with the Linux zip command, including practical examples, key options, and important precautions.

Linux gunzip Command: Decompress gzip Files

Linux gunzip Command: Decompress gzip Files

Learn how to decompress gzip Files with the Linux gunzip command, including practical examples, key options, and important precautions.

Linux Tutorial / File System Basics: Paths and Key Directories

Linux Tutorial / File System Basics: Paths and Key Directories

Understand the Linux directory tree, read absolute and relative paths, and learn what common directories such as /home, /etc, and /var are used for.

Linux top Command: Monitor Processes in Real Time

Linux top Command: Monitor Processes in Real Time

Learn how to monitor Processes in Real Time with the Linux top command, including practical examples, key options, and important precautions.

Linux uptime Command: Check Uptime and Load Averages

Linux uptime Command: Check Uptime and Load Averages

Learn how to use the Linux uptime command to check how long the system has been running and interpret load averages, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux curl Command: Make URL Requests and Inspect HTTP Responses

Linux curl Command: Make URL Requests and Inspect HTTP Responses

Learn how to make URL Requests and Inspect HTTP Responses with the Linux curl command, including practical examples, key options, and important precautions.

Linux umask Command: Control Default File Permissions

Linux umask Command: Control Default File Permissions

Learn how to control Default File Permissions with the Linux umask command, including practical examples, key options, and important precautions.

Linux xargs Command: Pass Standard Input as Command Arguments

Linux xargs Command: Pass Standard Input as Command Arguments

Learn how to pass Standard Input as Command Arguments with the Linux xargs command, including practical examples, key options, and important precautions.

Linux groups Command: Show a User's Group Memberships

Linux groups Command: Show a User's Group Memberships

Learn how to show a User's Group Memberships with the Linux groups command, including practical examples, key options, and important precautions.

Linux Tutorial / Hard Links vs. Symbolic Links in Linux: Differences and Examples

Linux Tutorial / Hard Links vs. Symbolic Links in Linux: Differences and Examples

Compare hard and symbolic links through inode and path behavior, then create both kinds of link and observe what happens when the original name changes.