Bash temp file: create and clean up with mktemp and trap

Summary

Create a temp file in Bash by calling mktemp, capturing the path, and immediately registering an EXIT trap to remove it; prefer mktemp -d and put all temporary artifacts inside that directory so one trap covers everything. The trap body should use single quotes with double-quoted variables and -- for rm, and mktemp must succeed before later commands use the path. Portability matters: macOS/BSD mktemp treats -t and suffix templates differently from GNU, so the reliable cross-platform form is mktemp "${TMPDIR:-/tmp}/name.XXXXXX" with at least six X's, or the temp-directory pattern. Remember that a second trap replaces the first, EXIT traps still run for normal exits and INT/TERM/HUP but not SIGKILL, and short-circuit cleanup commands inside a trap can accidentally change the script's exit status.

To create a temp file in Bash, call mktemp, capture the name it prints, and register an EXIT trap that deletes it. That takes three lines. Most of the trouble comes from what's around them: mktemp behaves differently on macOS and Linux, a second trap quietly replaces the first, and some exits skip the cleanup entirely.

Every example below was run on macOS 27 (the stock /bin/bash 3.2.57 and BSD mktemp) and on Ubuntu 24.04 (bash 5.2.21 and GNU coreutils 9.4). The output is copied from those runs, with the random part of each name being whatever came out that time.

The pattern to copy

#!/usr/bin/env bash
set -euo pipefail

tmpdir=$(mktemp -d)
trap 'rm -rf -- "$tmpdir"' EXIT

some_command > "$tmpdir/raw.txt"
sort -u "$tmpdir/raw.txt" > "$tmpdir/sorted.txt"
# ... more work ...

A few details in there matter:

  • Make a directory, not a file. Once you need a second temp file you just put it in $tmpdir, and one trap still cleans up everything.
  • The trap body is in single quotes. That way $tmpdir is expanded when the trap runs, not when you define it, and the inner double quotes protect paths that contain spaces. The -- stops rm from reading a path that starts with a dash as an option.
  • Set the trap right after mktemp. If anything fails between the two lines, the directory leaks.
  • With set -e, a failed mktemp stops the script. Without it, write tmpdir=$(mktemp -d) || exit 1. Otherwise $tmpdir is empty and later commands write to paths like /raw.txt.

mktemp creates the file with permissions -rw------- and the directory with drwx------, so other users on the machine can't read what you put there. The GNU coreutils manual says files are created "u+rw" and directories "u+rwx", minus umask. Both systems gave those modes in my runs.

Why not just use /tmp/myscript.$$

Older scripts often build the name from the process ID, as in /tmp/myscript.$$. Anyone on the box can predict that name and create the file (or a symlink with that name) before your script does. The BSD mktemp man page, which macOS ships too, says it directly: the scheme "is predictable and the race condition it creates is easy for an attacker to win." mktemp picks a random name and creates the file atomically, failing if the name already exists. For the same reason, skip mktemp -u. It only prints a name without creating anything, which brings the race back.

mktemp on macOS vs Linux

A bare mktemp works on both, but the files land in different places:

# macOS
/var/folders/b0/z24_sc_157157yxxp8p57d900000gn/T/tmp.0HxrXnFTW5
# Ubuntu
/tmp/tmp.bmQR9vPxkH

Things go wrong when you add a name. -t means different things on the two systems:

$ mktemp -t myscript
# macOS:  /var/folders/.../T/myscript.qyY7uIJ3iA
# Ubuntu: mktemp: too few X's in template 'myscript'   (exit 1)

$ mktemp -t myscript.XXXXXX
# macOS:  /var/folders/.../T/myscript.XXXXXX.7VdHpH2Ryn
# Ubuntu: /tmp/myscript.kU5Pyz

On BSD and macOS, -t takes a prefix and appends its own random part. GNU treats the argument as a template that needs its own run of X's, and its manual marks -t as deprecated in favour of -p. Neither form works the same way on both systems. This one does:

tmpfile=$(mktemp "${TMPDIR:-/tmp}/myscript.XXXXXX")

It gave /tmp/myscript.81m18c on Ubuntu and a path under /var/folders/.../T/ on macOS. macOS sets TMPDIR with a trailing slash, so the path came out with a harmless // in it.

The suffix trap

If you want the file to end in .json so another tool recognises it, the obvious template doesn't work on macOS:

$ mktemp /tmp/a.XXXXXX.json
# Ubuntu: /tmp/a.x4hdcU.json
# macOS:  /tmp/a.XXXXXX.json
$ mktemp /tmp/a.XXXXXX.json        # second run on macOS
mktemp: mkstemp failed on /tmp/a.XXXXXX.json: File exists

GNU replaces the last run of X's even when a suffix follows it. BSD only replaces trailing X's, so on macOS you get a fixed, guessable name and the script fails the second time it runs. GNU also has --suffix=.json, but macOS doesn't. The portable fix is the temp-directory pattern from above: create the directory with mktemp -d and name the file inside it whatever you like.

The two systems also differ on short templates. GNU requires at least three X's and rejects /tmp/a.XX. macOS accepted it and created /tmp/a.8K, which has only a few thousand possible names. Use six or more X's.

When the EXIT trap runs, and when it doesn't

The Bash manual says an EXIT trap "is executed when the shell exits". I ran the pattern from the top of this post and ended it in different ways, then checked whether the directory was still there:

How the script ended Exit status Temp dir removed?
Normal finish 0 Yes
A command failed under set -e 1 Yes
Ctrl-C (SIGINT to the process group) 130 Yes
kill (SIGTERM) 143 Yes
Terminal closed (SIGHUP) 129 Yes
kill -9 (SIGKILL) 137 No

Bash 3.2 and 5.2 gave the same results. You don't need to list INT TERM HUP next to EXIT in Bash. When Bash dies from one of those signals, it still runs the EXIT trap. Nothing can catch SIGKILL, though, and a power cut skips the trap too. If leftover files would hurt, give them a recognisable prefix and let a cron job or systemd-tmpfiles clear out old ones.

One thing that surprised me in testing: if you send SIGINT with kill to the script alone while it waits on a foreground command such as sleep 30, Bash doesn't act on it until sleep finishes. Ctrl-C works right away because the terminal sends the signal to the whole process group, sleep included.

A second trap replaces the first

trap doesn't stack. This script leaks $a:

a=$(mktemp); b=$(mktemp)
trap 'rm -f -- "$a"' EXIT
trap 'rm -f -- "$b"' EXIT   # replaces the first trap

After it ran, $b was gone and $a was still on disk, on both systems. This usually happens when a sourced helper library sets its own EXIT trap. The temp-directory pattern avoids it, because one trap covers every file. If you really need several cleanups, have one trap call a function and let that function do all the work:

cleanup() {
  rm -rf -- "$tmpdir"
  if [[ -n "${pidfile:-}" ]]; then rm -f -- "$pidfile"; fi
}
trap cleanup EXIT

Use the full if form there and not the shorter [[ -n "${pidfile:-}" ]] && rm -f -- "$pidfile". My first draft used the short form. When pidfile was unset, the test returned 1, and because it was the last command in the trap, a script that had otherwise succeeded exited with status 1. That happened on both Bash 3.2 and 5.2, and it's the kind of bug that breaks a CI job without telling you why. With the if version, the script exited 0.

To see what's currently registered, run trap -p EXIT. It prints trap -- 'rm -rf -- "$tmpdir"' EXIT.

TRAP BASH SHELL SCRIPT MACOS MKTEMP TEMP FILE

  RELATED

  COMMENTS

0

No comment for this article.