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

●1 ●21 ●79
calendar_today • 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.

2 Comments

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

More Posts

My 30-day log cleanup kept a file that was 30 and a half days old

BashSnippets - Oct 8

I escaped the dot correctly and sed still rewrote a file marked DO NOT CHANGE

BashSnippets - Oct 13

ShellCheck rates SC2086 as info. It let rm delete two files I never named.

BashSnippets - Sep 29

bash ran a path that no longer existed, and exited 127

BashSnippets - Oct 21

sed 's/port/listen_port/g' rewrote four lines of a four-line config

BashSnippets - Oct 1
chevron_left
3.8k Points • 101 Badges
North America • bashsnippets.xyz
68Posts
31Comments
10Connections
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)

2 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!