I sent my report script SIGTERM mid-write. Yesterday's output survived intact.

●1 ●8 ●58
calendar_today ago • schedule1 min read

A script that writes straight to the path a consumer reads can die halfway and leave a torn file that everything downstream loads as complete. No error appears anywhere, because the only process that failed is gone. I tested the fix the unfriendly way on bash 5.3.9: a CSV generator with a sleep 30 planted between rows, killed with SIGTERM one second in.

TMP_FILE=$(mktemp)
cleanup() { local code=$?; rm -f "$TMP_FILE"; exit "$code"; }
trap cleanup EXIT
generate_rows > "$TMP_FILE"
mv "$TMP_FILE" "$FINAL_PATH"

Exit 143, which is 128 plus signal 15. The temp file was gone, and out.csv still held the previous run's three complete lines. Stale is something monitoring can see. Torn is not.

EXIT fires on normal completion, an explicit exit 1, a set -e abort and after a handled signal, which is why this is five lines instead of twenty. And because mv on one filesystem is atomic, being half-written and being at the published path are never true at once. Even kill -9, which no trap catches, cannot publish a torn file.

The ordering is the part people move. I ran four handler variants against a script ending in exit 3, and only one exited 0: rm -f first, then local code=$?. It captured rm's success and laundered the failure. Capture first, clean second, exit last.

The complete script, subshell scoping rules and a line-by-line breakdown are on the trap cleanup page for temp files and atomic writes.

1 Comment

0 votes
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

My Nginx Died at 2 AM and Nobody Noticed for 6 Hours. Now I Have a Watchdog Script

BashSnippets - May 21

Your AI Doesn't Just Write Tests. It Runs Them Too.

Kevin Martinez - May 12

I Wrote a Script to Fix Audible's Unreadable PDF Filenames

snapsynapseverified - Apr 20

Who owns that port? One ss flag answers it without sudo

BashSnippets - Sep 16

My Script Crashed and Left a Lock File Behind. Every Run After That Refused to Start.

BashSnippets - Jun 11
chevron_left
3.2k Points • 67 Badges
North America • bashsnippets.xyz
48Posts
26Comments
7Connections
Linux user who got tired of Googling the same bash commands every time I sat down at a terminal. Sta... Show more

Related Jobs

View all jobs →

Commenters (This Week)

3 comments

Contribute meaningful comments to climb the leaderboard and earn badges!