Temporary Files with mktemp
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.
/tmpis 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 (often644), 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:
-ttreats the template as a plain filename and places it in$TMPDIRor/tmp.-p DIR(also--tmpdir=DIR) places it inDIR. The long form--tmpdirwithout a value uses$TMPDIRif 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 thatmktempexists 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.mktempis available on Linux, macOS and the BSDs. The basicmktempandmktemp -dforms work on all of them; the long options,--suffixand-pdiffer 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
mvis an atomic rename. The leading dot hides it from a plainls. - The trap removes the temporary file if
awkfails or the script is interrupted. After a successfulmv, the file no longer exists under the old name, andrm -ffinds nothing to remove. awk '!seen[$0]++'prints each line the first time it appears (lesson 109).chmod --referencekeeps 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.