Temporary Files with mktemp

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 113 of 205

Scripts often need a place to keep data for a short time: the sorted version of a file before it replaces the original, the output of one command that two later commands read, a downloaded archive that is unpacked and then thrown away. mktemp creates such a temporary file or directory with a unique, unpredictable name and prints that name, so the script can store it in a variable and use it.

tmp=$(mktemp)
echo "$tmp"
/tmp/tmp.hJLfH4yNTI

The random part of the name is different on every run. The file already exists when mktemp returns, it is empty, and only its owner can read or write it.

Why Not Just Use /tmp/myscript.txt?

The obvious approach is to pick a fixed name, such as /tmp/myscript.txt or /tmp/myscript.$$ (where $$ is the script's process ID). Both have real problems:

  • Collisions. Two copies of the script running at the same time, for example two cron jobs or two users, write to the same file and corrupt each other's data. With $$, a new process can reuse the ID of an old one whose file was never removed.
  • Predictability. /tmp is shared by every user on the system. Someone who knows the name in advance can create that file first, or create a symbolic link with that name pointing at one of your files. When the script then writes to "its" temporary file, it writes to the attacker's file or overwrites the link target with your permissions. This class of bug is called a temporary-file race, and it has caused real security vulnerabilities.
  • Permissions. A file created with > gets the permissions allowed by the current umask (often 644), so other users may be able to read sensitive data from it.

mktemp avoids all three. It generates a random name, creates the file in a single step that fails if the name already exists (so it never follows a planted link), and gives the file mode 600 (read and write for the owner only):

stat -c '%a %s' "$tmp"
600 0

The mode is the same even when the umask is permissive:

(umask 000; f=$(mktemp); stat -c '%a' "$f"; rm -f -- "$f")
600

Creating Temporary Directories with -d

-d creates a directory instead of a file. Its mode is 700, so only the owner can list, enter or create files in it:

d=$(mktemp -d)
echo "$d"
ls -ld "$d" | cut -c1-10
/tmp/tmp.7NwIkBC609
drwx------

A private directory is the most convenient choice when a script needs several temporary files. Files created inside it with ordinary names such as "$d/list.txt" are safe, because no one else can reach the directory, and cleaning up means removing one directory.

Choosing the Name and Location

Templates

mktemp accepts a template in which a run of X characters is replaced by random letters and digits. The template can include a directory:

mktemp /tmp/report.XXXXXX
/tmp/report.76XG6T

More X's give more possible names. GNU mktemp requires at least three consecutive X's:

mktemp /tmp/a.XX
mktemp: too few X's in template '/tmp/a.XX'

The default template, used when none is given, is tmp.XXXXXXXXXX (ten X's). A recognizable prefix such as the script name makes leftover files easy to identify: mktemp -t backup.XXXXXXXX.

The Temporary Directory: -t, -p and TMPDIR

Where should a template without a directory go? The conventional answer is the directory named by the TMPDIR environment variable, or /tmp when TMPDIR is not set. GNU mktemp offers two options for this:

  • -t treats the template as a plain filename and places it in $TMPDIR or /tmp.
  • -p DIR (also --tmpdir=DIR) places it in DIR. The long form --tmpdir without a value uses $TMPDIR if set, else /tmp.
mktemp -t backup.XXXXXXXX
mkdir work
mktemp -p work
mktemp -p work log.XXXX
/tmp/backup.E9HZbysF
work/tmp.fG61jAenZO
work/log.oD0n

TMPDIR changes the default location for mktemp and for many other programs:

TMPDIR=$PWD/mytmp mktemp
/home/ana/project/mytmp/tmp.JdjXpPI2US

Respecting TMPDIR matters on shared servers and in containers, where administrators often point it at a larger or private disk.

Adding a Suffix

Some programs care about the file extension. --suffix adds text after the random part:

mktemp --suffix=.csv
/tmp/tmp.D4HWWSjFCJ.csv

GNU mktemp also accepts a template in which text follows the X's, such as /tmp/data.XXXXXX.csv, and treats that text as the suffix. BSD and macOS mktemp expect the X's at the end of the template, so --suffix and trailing text are not portable.

Checking That mktemp Succeeded

mktemp can fail, for example when the target directory does not exist, is full or is not writable. It then prints an error to standard error, prints nothing to standard output, and returns status 1:

mktemp -p /nonexistent
mktemp: failed to create file via template '/nonexistent/tmp.XXXXXXXXXX': No such file or directory

If the script carries on, tmp is empty, and a later command such as sort data.txt > "$tmp" fails with a confusing message, or worse, rm -rf "$tmp"/* expands to rm -rf /*. Always check the result:

tmp=$(mktemp) || { echo "cannot create temp file" >&2; exit 1; }

An assignment from a command substitution has the exit status of the command (lesson 48), so || runs the error branch exactly when mktemp fails. Do not combine the check with local in a function (local tmp=$(mktemp) always has status 0, as lesson 92 explains); declare the variable first and assign it on a separate line. -q suppresses mktemp's own message when the script prints its own.

Removing Temporary Files Automatically

A temporary file that is never removed fills /tmp over time and may leave sensitive data behind. Removing it at the end of the script is not enough, because the script can stop early: an exit in an error branch, a failed command under set -e, or Ctrl + C.

trap ... EXIT registers a command that Bash runs whenever the script ends, however it ends (lessons 123 and 124 cover traps in detail):

#!/usr/bin/env bash
tmp=$(mktemp) || exit 1
trap 'rm -f -- "$tmp"' EXIT

echo "working in $tmp"
echo data > "$tmp"
exit 3
working in /tmp/tmp.XXXXXXXXXX

The script ended with status 3, and the temporary file no longer existed afterwards. The trap command is in single quotes, so $tmp is expanded when the trap runs, not when it is set; the -- protects against a name that starts with a dash.

For a temporary directory, the pattern is the same with rm -rf:

#!/usr/bin/env bash
workdir=$(mktemp -d) || exit 1
trap 'rm -rf -- "$workdir"' EXIT

cd "$workdir" || exit 1
touch a.part b.part
ls
a.part
b.part

After the script finished, the directory and both files were gone. Set the trap immediately after mktemp succeeds, and only after it succeeds, so the trap never runs rm -rf on an empty or wrong path.

Replacing a File Safely

A common job is to transform a file and write the result back to the same name. Writing directly to the input does not work, because > empties the file before the command reads it (lesson 57). A temporary file solves this:

printf '3\n1\n2\n' > data.txt
tmp=$(mktemp) || exit 1
sort data.txt > "$tmp" && mv -- "$tmp" data.txt
cat data.txt
1
2
3

The && means the original is replaced only when sort succeeded, so a failure leaves the old file untouched. One side effect is easy to miss: mv moves the temporary file itself into place, so the new data.txt carries the temporary file's permissions:

stat -c '%a' data.txt
600

If the original was 644, other users can no longer read it. Two ways keep the original permissions:

# copy the content back; data.txt keeps its own permissions
sort data.txt > "$tmp" && cat "$tmp" > data.txt
rm -f -- "$tmp"

# or give the temporary file the original's permissions before moving it
sort data.txt > "$tmp" && chmod --reference=data.txt "$tmp" && mv -- "$tmp" data.txt

Both left a 644 file as 644 in testing. chmod --reference is a GNU option.

mv within one file system is a rename, which happens in one step: other programs see either the complete old file or the complete new one, never a half-written file. A temporary file in /tmp may be on a different file system from the target, and then mv has to copy the data instead. To keep the atomic rename, create the temporary file in the target's own directory:

tmp=$(mktemp -p "$(dirname -- "$target")") || exit 1

Working with Several Temporary Files

comm compares two sorted files, which makes it a good example of a command that needs real files on disk:

a=$(mktemp) b=$(mktemp)
printf 'b\na\n' > "$a"
printf 'a\nc\n' > "$b"
sort -o "$a" "$a"
sort -o "$b" "$b"
comm -12 "$a" "$b"
rm -f -- "$a" "$b"
a

comm -12 prints only the lines common to both files. For many temporary files, one private directory with ordinary names inside it is easier to manage and clean up than a variable per file. Process substitution (lesson 151) can often replace short-lived files altogether, as in comm -12 <(sort list1) <(sort list2).

Other Options

  • -u (--dry-run) prints a name without creating anything. Using that name later brings back the race that mktemp exists to prevent, and the GNU help text marks the option as unsafe.
  • -q (--quiet) hides the error message on failure; the exit status is still 1.
  • mktemp is available on Linux, macOS and the BSDs. The basic mktemp and mktemp -d forms work on all of them; the long options, --suffix and -p differ between versions. It also works from Dash and other shells, because it is an external program, not a Bash builtin.

A Complete Example

This script removes duplicate lines from a file given as an argument while keeping the original order, writes the result next to the original, and cleans up on every path:

#!/usr/bin/env bash
file=${1:?usage: dedupe.sh FILE}
[ -f "$file" ] || { echo "dedupe.sh: no such file: $file" >&2; exit 1; }

tmp=$(mktemp -p "$(dirname -- "$file")" .dedupe.XXXXXX) || exit 1
trap 'rm -f -- "$tmp"' EXIT

awk '!seen[$0]++' "$file" > "$tmp" || exit 1
chmod --reference="$file" "$tmp"
mv -- "$tmp" "$file"
  • The temporary file is created in the same directory as the target, so the final mv is an atomic rename. The leading dot hides it from a plain ls.
  • The trap removes the temporary file if awk fails or the script is interrupted. After a successful mv, the file no longer exists under the old name, and rm -f finds nothing to remove.
  • awk '!seen[$0]++' prints each line the first time it appears (lesson 109).
  • chmod --reference keeps the original permissions.

Run on sub dir/list.txt (lines b a b c a, mode 640), the script left the lines b, a and c, kept mode 640, and left no .dedupe.* file behind. Run on a missing file, it printed dedupe.sh: no such file: nofile and returned status 1.

The examples were run with Bash 5.2.21, GNU coreutils 9.4 (mktemp, stat, sort, comm) and Dash. Random parts of names differ on every run, and the /home/ana/project path is a sample working directory.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Temporary Files with mktemp and get answers drawn from it.

Signed-in readers only.