Add robust error handling and a cleanup trap to a fragile deploy script
A deploy helper fetches a report into a temp file, transforms it, and uploads it — but it never removes the temp file, and a failure midway leaves a stale file behind while the script keeps going as if nothing broke.
Constraints: the temp file must be deleted on EVERY exit path (success, error, or signal); a mid-pipeline failure must abort the run.
#!/usr/bin/env bash
tmp=$(mktemp)
curl -s "$REPORT_URL" > "$tmp"
jq '.rows' "$tmp" > report.json
upload report.json
Add strict mode and a cleanup trap.
Turn on strict mode with set -euo pipefail so a failed command, a broken pipe stage, or an unset variable aborts the run. Right after mktemp, register trap 'rm -f "$tmp"' EXIT: the EXIT trap fires on a normal finish, an error abort, and a caught signal, so the temp file is always removed.
- ✗Registering the
trapbeforemktemp, so an early failure never cleans up - ✗Believing plain
set -ealso removes temp files without atrap - ✗Using a
SIGINT- orRETURN-only trap, missing the error-abort exit path
- →Why register the
traponEXITrather than onSIGINTandSIGTERMseparately? - →How does
set -ebehave for a command whose failure you deliberately tolerate?
Solution
The script holds a temp file but never removes it and never checks for failure. Two things fix it: strict mode, and a single cleanup trap set right after the file is created.
#!/usr/bin/env bash
set -euo pipefail
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT # remove the file on any exit path
curl -sf "$REPORT_URL" > "$tmp" # -f: an HTTP error → non-zero → abort
jq '.rows' "$tmp" > report.json
upload report.json
unset variable (e.g. an empty $REPORT_URL), and -o pipefail surfaces a failure in any pipeline stage.
EXIT trap runs on a normal finish, on a set -e abort, and on a caught signal — so the temp file is always removed, with exactly one handler.
instead of uploading a broken report.
set -euo pipefail—-eaborts on the first failed command,-ucatches antrap 'rm -f "$tmp"' EXITis registered immediately aftermktemp. Thecurl -sfadds-fso an HTTP 404/500 returns non-zero andset -eaborts