Safe Atomic File Update

Medium Shell Reliability Asked at Google
Solve this problem

Update a configuration file so a power loss mid-write can never leave a truncated file behind. Write to a temporary file, sync it, then rename over the original.

Constraints

  • The temporary file must be on the same filesystem as the target.
  • Must sync before the rename.
  • Preserve the original file's permissions.
  • Clean up the temporary file on any failure.
  • Exit non-zero if the target directory is not writable.
  • POSIX sh with a trap for cleanup.
Starter codeShell
1#!/bin/sh2# TODO: atomically replace a config file