Safe temporary files and atomic writes

Intermediate · 7 min

Create temp files with mktemp instead of guessable names, clean up with a trap, and replace files atomically with write-then-mv. BSD mktemp differences noted.

Before thisTraps and cleanupStrict mode - set -e, -u and pipefailHard and symbolic linksPermissions and chmodStructure and style: main functions and shfmt

Putorius Linux Tutorials · 7 min

Safe temporary files and atomic writes

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Putorius Linux TutorialsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A temp file named from something guessable, such as /tmp/job.$$, can be pre-created as a symlink by someone else, so your write lands where they chose. mktemp picks an unpredictable name and creates the file for you with mode 600.
  • Pair mktemp with trap 'rm -rf "$tmp"' EXIT so cleanup runs on a normal exit, an error under set -e and Ctrl-C. SIGKILL cannot be trapped, so it still leaves the temp behind.
  • Writing the final file directly means a crash leaves it half written. Write to a temp file in the same directory, then mv it over the target. A rename within one filesystem is atomic.
  • The temp file must be on the same filesystem as the target. mv across filesystems is a copy and delete, which is not atomic.
  • GNU and BSD mktemp differ: BSD ignores a suffix after the Xs and may ignore TMPDIR. Put the Xs at the end of the template, and test on both systems.

Two separate problems

A script usually needs scratch space: a sorted copy, a download in progress, a file it will assemble and then publish. Two things go wrong.

First, whose file is it? /tmp is shared. If your script writes to a name another user can predict, they can plant something there first. Second, what state is the real file in if you die halfway? If you write the final output in place and the script is killed, whoever reads it next gets a truncated file.

Both have short, boring solutions. I tested them on macOS with Bash 5.3, in a scratch directory.

mktemp

mktemp creates a file with a random name and returns the name. It makes the file itself, in one step, so no one else can grab the name in between:

$ f=$(mktemp)
$ echo "$f"
/var/folders/.../T/tmp.Zc4yhNM8ok
$ ls -l "$f" | awk '{print $1}'
-rw-------@

Mode 600, readable only by you. -d makes a directory instead, with mode 700 (drwx------), which is the better choice when you need several files, because one cleanup removes it all.

To control the name, give a template whose trailing Xs are replaced:

$ mktemp "$TMPDIR/report.XXXXXX"
./tmp/report.v8cnYc
$ mktemp "$TMPDIR/report.XXXXXX.txt"
./tmp/report.XXXXXX.txt

Look at the second one. BSD mktemp only replaces Xs at the end, so the suffix version created a file literally named report.XXXXXX.txt every time, with no randomness at all. GNU mktemp accepts a suffix, but I did not run it, so check its man page. Portable code puts the Xs last. Also, on this Mac a plain mktemp ignored the TMPDIR I had exported and made the file under /var/folders/.... GNU’s documentation says it honours TMPDIR. If the location matters, give a full template or use mktemp -d once and put your files inside.

Why not $$

The tempting shortcut is /tmp/job.$$, the shell’s PID. PIDs are guessable. I pre-created a symlink at that name pointing at an important file, then wrote to it the way a naive script would:

$ echo "precious" > victim.txt
$ ln -s "$PWD/victim.txt" "$TMPDIR/job.$$"
$ echo "attacker content ignored" > "$TMPDIR/job.$$"; cat victim.txt
attacker content ignored

The redirect followed the link and overwrote victim.txt. The message I printed was a joke, but the content was gone. In a shared /tmp, this is a real attack. With the shell option noclobber (set -C), the same write is refused:

$ ( set -C; echo overwritten > "$TMPDIR/job.$$" )
...: cannot overwrite existing file
$ cat victim.txt
precious

That works as a safety net, but mktemp is the actual answer, since it never reuses a name.

Cleanup with a trap

A temp file should go away however the script ends. Use a trap on EXIT:

#!/usr/bin/env bash
set -euo pipefail
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
echo "working in ${tmp##*/}"
echo data > "$tmp/scratch"
false
$ bash withtrap.sh; echo "exit=$?"
working in tmp.5eb6OmcWxn
exit=1

The script died at false under set -e, and the directory was cleaned up anyway. Note the single quotes: the $tmp must be expanded when the trap fires, not when it is set, though here both give the same result. There is one limit. SIGKILL cannot be caught, as the signals lesson explained. I killed a script with kill -9 after it made a temp directory, and the directory stayed:

$ bash -c 'tmp=$(mktemp -d "$TMPDIR/kk.XXXXXX"); trap "rm -rf $tmp" EXIT; kill -9 $$'
$ ls "$TMPDIR" | grep -c kk
1

Nothing can be done about that from inside the script. Periodic cleanup of old temp directories is the only recourse.

Atomic replacement

Now the second problem. Here is a “config” file being rewritten, with the script killed halfway through:

$ echo "good v1" > config.txt
$ bash -c 'echo "new line 1" > config.txt; kill -9 $$; echo "new line 2" >> config.txt'
after crash: new line 1

The old good content is gone, replaced by half a new file. Writing to a temp file in the same directory and then renaming it over the target avoids this:

$ echo "good v1" > config.txt
$ bash -c 'tmp=$(mktemp "config.txt.XXXXXX"); echo "new line 1" > "$tmp"; kill -9 $$; echo "new line 2" >> "$tmp"; mv "$tmp" config.txt'
after crash: good v1

The reader still sees the complete old file, and the half-written temp is a stray file you can clean up. When the script finishes, mv swaps the new file in with a single rename:

$ bash -c 'tmp=$(mktemp config.txt.XXXXXX); echo x > "$tmp"; ls -i "$tmp"; mv "$tmp" config.txt; ls -i config.txt'
temp inode 61664497
after mv inode 61664497

The same inode before and after: the file was renamed, not copied. That is why readers see either the old or the new file, never a mix, and it is what editors and package managers do.

Two cautions. The temp file must be on the same filesystem as the target, because a rename can only be atomic within one filesystem. mv across filesystems silently becomes copy-then-delete, with the same half-file window. Putting the temp file in the target’s directory, as above, guarantees it. I did not test a cross-filesystem move. Second, mktemp makes mode 600 files, and after mv the target is 600 too (-rw------- in my run), whatever mode the old file had. Run chmod (see permissions) on the temp file before the move if the target needs a different mode. Atomic rename also does not make the data durable against power loss, which needs an fsync that shell has no direct command for.

About the video

“How to Securely Work with Temporary Files in Linux Shell Scripting” is a 6-minute 45-second video from Putorius Linux Tutorials, published March 2023. Its chapters are: introduction to temp files, security risks (1:33), cleanup and best practices (2:06), the mktemp implementation (3:48) and automating safe exit (5:19). That covers the mktemp and cleanup-with-trap parts of this lesson. I could not read a transcript, so I do not know whether it touches the write-to-temp-then-mv pattern, and I found no video that covers atomic replacement in shell. It is in English.

Where this fits

A script that handles files safely also has to talk to the person running it: usage messages, logs and honest exit codes are in logging, usage messages and exit codes.

Check yourself

  1. 01Why is echo data > /tmp/myscript.$$ unsafe on a shared machine?

    The name is predictable, so another user can create a symlink there first. Your redirect follows it and overwrites whatever it points to. mktemp makes an unguessable name and creates the file itself.

  2. 02What does the trap on EXIT do that rm at the end of the script does not?

    It runs on every way out: errors under set -e, Ctrl-C, and early exit calls. An rm at the end only runs if the script gets there.

  3. 03How do you update config.txt so a reader never sees half a file?

    Write the new content to a temp file in the same directory, then mv it onto config.txt. The rename swaps the file in one step.

  4. 04You used mktemp /tmp/data.XXXXXX.csv on a Mac and got a file literally named data.XXXXXX.csv. Why?

    BSD mktemp only replaces trailing Xs. Use data.XXXXXX and add any suffix after creating it, or test on the target system.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark