Interview Prep/Shell Scripting/Arguments, I/O, here-docs, process substitution and subshells

How do you write a file atomically so readers never see a half-written version?

AdvancedConceptArguments, I/O, here-docs, process substitution and subshells
Answer

Write to a temp file on the same filesystem, flush it, then mv it over the target. rename(2) is atomic within a filesystem: readers see either the old or the new file.

tmp=$(mktemp "/etc/nginx/conf.d/.upstreams.XXXXXX")
generate_upstreams > "$tmp"
nginx -t -c /etc/nginx/nginx.conf || { rm -f "$tmp"; exit 1; }   # validate first
chmod 0644 "$tmp"
mv -f -- "$tmp" /etc/nginx/conf.d/upstreams.conf
systemctl reload nginx

mv across filesystems (e.g. from /tmp to /etc) becomes copy-then-delete and is not atomic. The same pattern applies to symlink switches: ln -sfn new current.tmp && mv -T current.tmp current.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arguments, I/O, here-docs, process substitution and subshells