Error handling and cleanup traps
Keep failure visible and remove temporary work on every exit path.
Fail where you understand the error
Check a command near the place you know what it was meant to do: if ! cp ...; then ...; fi. Send diagnostics to stderr and choose a nonzero exit status. Avoid claiming success just because a later cleanup command succeeded.
set -e has exceptions: commands tested by if, parts of &&/|| lists, pipeline behavior and function call contexts can all affect it. It is not a replacement for deliberate error handling. With ! command, $? is the status of the negation; save the original status before negating it when you need that exact value.
Register cleanup once
trap cleanup EXIT runs a cleanup function when this Bash process exits normally or through an explicit exit. Keep the trap expression single-quoted when it should expand variables at cleanup time. Handle HUP, INT and TERM explicitly when needed; SIGKILL cannot be trapped.
This small exercise uses a named .stage directory and refuses to overwrite one that already exists. Real concurrent tools normally use mktemp -d with a template. Stop destroys the entire VM and restores the last completed snapshot, so browser interruption does not depend on a shell trap running.
cleanup() { rm -f './temporary.txt'; }
trap cleanup EXIT
printf 'working\n' > temporary.txt
printf 'The EXIT trap will remove the temporary file.\n'
Put it into practice.
Create a new `.stage` directory and register cleanup to remove it on success or failure. Refuse a pre-existing .stage directory. Copy `input.txt` through `.stage/report.txt` into `report.txt`. On success print `Report ready` and exit 0. If input.txt is missing, print `Cannot read input.txt` to stderr and exit nonzero, leaving no .stage directory and no new report. Preserve input.txt.
See an explained solution
if ! mkdir './.stage' 2>/dev/null; then printf 'Staging directory exists\n' >&2; exit 1; fi
cleanup() { rm -rf './.stage'; }
trap cleanup EXIT
trap 'exit 1' HUP INT TERM
if ! cat './input.txt' > './.stage/report.txt' 2>/dev/null; then
printf 'Cannot read input.txt\n' >&2
exit 1
fi
mv './.stage/report.txt' './report.txt' || exit 1
printf 'Report ready\n'
The trap is shared by success and failure paths. Reports are moved into place only after the input has been read successfully.