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.
More on Arguments, I/O, here-docs, process substitution and subshells
How does `getopts` work? Show a complete example.IntermediateWhat is the difference between `getopts` and `getopt`?AdvancedExplain file descriptors 0, 1 and 2 and the main redirection operators.BeginnerWhy is `cmd 2>&1 > file` different from `cmd > file 2>&1`?AdvancedWhat is a here-document, and what is the difference between `<<EOF`, `<<'EOF'` and `<<-EOF`?BeginnerWhat is a here-string (`<<<`)?Intermediate