TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Safe Temp Files, Atomic Writes and Locks

Safe Temp Files, Atomic Writes and Locks

Automation scripts write files that other things read: a generated config that nginx loads, a JSON status file a dashboard polls, a cache a later run reuses. Three problems come up again and again: temporary files in predictable places, readers that see a half-written file, and two copies of the same script running at once. Each has a small, standard fix.

Temporary files: always mktemp

/tmp/myscript.tmp or /tmp/myscript.$ are predictable names. On a shared machine another user can create that path first, or a symlink with that name pointing at one of your files, and your script then writes where they chose. Two runs of the same script also collide. mktemp creates a new file or directory with a random name and permissions only you can read:

bash · try it yourself
umask 022
f=$(mktemp)
d=$(mktemp -d)
stat -c '%A %U' "$f" "$d"
case $f in /tmp/tmp.*) echo "file in /tmp with a unique suffix" ;; esac
TMPDIR=$PWD/scratch; mkdir -p "$TMPDIR"; export TMPDIR
g=$(mktemp --suffix=.json report.XXXXXX)
case $g in report.??????.json) echo "relative template: created in the current directory" ;; esac
h=$(mktemp -t report.XXXXXX)
case $h in "$TMPDIR"/report.*) echo "-t template: created under \$TMPDIR" ;; esac
rm -rf -- "$f" "$d" "$g" "$h"
-rw------- learner
drwx------ learner
file in /tmp with a unique suffix
relative template: created in the current directory
-t template: created under $TMPDIR

The random part of the name differs on every run, so the session checks the pattern rather than printing it. Use mktemp -d for anything that needs several files, register a cleanup trap right after it (trap: Cleanup, Signals and Exit Status), and honour $TMPDIR: CI systems and containers often point it at a larger or faster disk.

Atomic writes: write next to the target, then rename

Writing straight into the real file (generate > /etc/app/config.json) has two failure modes: a reader that opens the file mid-write sees half of it, and a generator that fails halfway leaves a truncated file behind. Instead, write to a temporary file in the same directory and mv it over the target. A rename within one file system is atomic: readers see the old file or the new one, never a mix.

bash · try it yourself
cat > publish.sh <<'SCRIPT'
set -euo pipefail
target=status.json
publish() {
  local tmp
  tmp=$(mktemp "$target.XXXXXX")              # same directory as the target
  if "$@" > "$tmp" && jq empty "$tmp"; then    # generate, then validate
    chmod 644 "$tmp"
    mv -f -- "$tmp" "$target"                  # atomic replace
  else
    rm -f -- "$tmp"
    return 1
  fi
}
good() { echo '{"healthy": 3, "down": 0}'; }
bad()  { echo '{"healthy": 3, "do'; }          # truncated output
publish good && echo "published: $(cat "$target")"
publish bad  || echo "bad output rejected, target still: $(cat "$target")"
ls
SCRIPT
bash publish.sh
published: {"healthy": 3, "down": 0}
jq: parse error: Unfinished string at EOF at line 2, column 0
bad output rejected, target still: {"healthy": 3, "down": 0}
publish.sh
status.json

The broken output never reached status.json, and the temporary file was removed. The checks are explicit (if … && …) rather than left to set -e, because publish bad || … calls the function as a condition, where errexit is off (Strict Mode and Its Traps, trap 1). The mktemp template keeps the temporary file in the same directory: mv across file systems (say from /tmp to /etc) is a copy plus a delete, which is not atomic.

Note: sed -i, yq -i and most "in-place" editors already work this way: they write a new file and rename it. That also means they replace the file's inode, which breaks hard links and anything that watches the old inode.

One run at a time: flock

Cron, CI and impatient humans all start scripts again before the last run finished. Two backups writing to the same destination, or two deploys racing, corrupt state. flock (from util-linux) takes a lock on a file; with -n a second instance gives up immediately instead of waiting:

bash · try it yourself
cat > nightly.sh <<'SCRIPT'
#!/usr/bin/env bash
set -euo pipefail
exec 9> nightly.lock                       # open the lock file on descriptor 9
if ! flock -n 9; then
  echo "$1: another run is in progress, exiting" >&2
  exit 75                                  # EX_TEMPFAIL: try again later
fi
echo "$1: got the lock"
touch "running.$1"                         # tell the demo we are inside
sleep "${2:-0}"
echo "$1: done"
SCRIPT
chmod +x nightly.sh
./nightly.sh first 1 &
for _ in $(seq 50); do [ -e running.first ] && break; sleep 0.1; done
./nightly.sh second; echo "second exited with $?"
wait
./nightly.sh third; echo "third exited with $?"
first: got the lock
second: another run is in progress, exiting
second exited with 75
first: done
third: got the lock
third: done
third exited with 0

The lock belongs to the open file descriptor, so the kernel releases it when the process exits, however it exits, even after kill -9. That is the big advantage over "PID files" and mkdir locks, which a crashed run leaves behind. Use flock -w 30 9 to wait up to 30 seconds instead of giving up. A single line in a crontab does the same for any command: flock -n /var/lock/backup.lock /usr/local/bin/backup.

Exit status 75 (EX_TEMPFAIL from sysexits.h) tells a scheduler "not now" rather than "broken"; systemd and many job runners can be told to treat it as a soft failure.

Test yourself

Why should a script use mktemp instead of /tmp/myscript.$?

  1. $ is not a valid variable
  2. Predictable names can be pre-created or replaced by a symlink by another user, and runs can collide
  3. mktemp files are deleted automatically
  4. /tmp is read-only

Why does the atomic-write pattern create the temporary file in the target's directory?

  1. So ls shows it
  2. A rename is only atomic within one file system; mv across file systems copies and deletes
  3. mktemp cannot write to /tmp
  4. Permissions are copied from the directory

What happens to a flock lock when the process holding it is killed with kill -9?

  1. The lock stays until reboot
  2. The kernel releases it when the file descriptor is closed at process exit
  3. The next run must delete the lock file
  4. flock prevents kill -9