brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: write to a temp file, then mv, so a shell script never leaves half a file

Shell
~/tips/tip-shell-write-temp-then-mv

tmp=$(mktemp ./hosts.json.XXXXXX)

Replace a config or data file in one step, so readers never see it half written.

If a script writes straight into config.json and dies halfway, the next program that reads it gets half a file. Writing somewhere else first and renaming at the end avoids that.

Create the temp file in the same folder as the target, fill it, and move it over the old one:

tmp=$(mktemp ./hosts.json.XXXXXX)
generate_hosts > "$tmp" || { rm -f "$tmp"; exit 1; }
chmod 644 "$tmp"
mv "$tmp" hosts.json

On the same filesystem, mv is a rename, and a rename replaces the old file in one step. Anyone who opens hosts.json gets either the complete old version or the complete new one, never a mix. If the generator fails, the old file stays as it was.

I like the extra safety net too: a broken run leaves the working file alone, so nothing downstream breaks because of a bad night.

Keep the temp file in the same folder. With /tmp on another filesystem, mv has to copy and delete, and that copy is not atomic anymore. Also note that mktemp creates the file with mode 600, which is why the example sets the permissions before the rename. A file that other users or services need to read would otherwise suddenly be private.

Further reading: rename(2) manual page, mktemp invocation (GNU coreutils)

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link