Safe Atomic File Update
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.
1#!/bin/sh2# TODO: atomically replace a config file