How-to, notes, thoughts

Search

Search loads after the Pagefind index is built into public/pagefind.


Atomic Writes for Shell Scripts

A shell script that writes state directly to its final path has a small but sharp failure mode: readers can catch the file halfway through the write. That matters for JSON status files, lock metadata, generated configs, and anything another process may parse while the script is still running.

The usual pattern is to write the full content to a temporary file in the same directory, then rename it into place. On POSIX filesystems, mv within the same filesystem is atomic: readers see either the old complete file or the new complete file, not a torn mix of both.

tmp="$(mktemp "$(dirname "$target")/.tmp.XXXXXX")"
trap 'rm -f "$tmp"' EXIT

render_status > "$tmp"
mv "$tmp" "$target"
trap - EXIT

The same-directory detail is not cosmetic. If the temporary file lives on another filesystem, the move becomes a copy-and-delete operation, which loses the atomic guarantee. For scripts that act like tiny control planes, this is one of those boring habits that prevents interesting outages. Boring is underrated.