Atomic File Writes in Bash: How a Temp File and EXIT Trap Prevent Silent Data Corruption
A software developer demonstrated a Bash scripting pattern that prevents consumers from reading incomplete output files when a script is interrupted mid-execution. The approach uses mktemp to write data to a temporary file first, then atomically moves it to the final destination only on successful completion. An EXIT trap ensures the temporary file is deleted if the script is killed by a signal, fails due to set -e, or exits normally, leaving the previously published file intact. Testing on Bash 5.3.9 confirmed that sending SIGTERM mid-run preserved the last complete output while cleanly removing the partial temp file. The developer also highlighted a critical ordering bug in the cleanup handler: capturing the exit code must be the very first line, as running even a successful rm beforehand will overwrite the status with zero, causing monitoring tools to report false success.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in