EXIT, INT and TERM cleanup
An EXIT trap runs when the shell exits normally or through many handled failure paths. Capture the incoming status before cleanup and preserve it explicitly. INT and TERM are real signals; handlers may choose to exit with conventional statuses 130 and 143 (128 plus the signal number on this Linux fixture). A signal trap does not automatically terminate the script. Here each signal is sent only to a newly launched foreground child Bash by that child itself, never to an unrelated process or group. Use a private workspace and known file names; remove only artifacts you own. In production track child identities, forward signals only to intended live children and reap them; a foreground wait can delay trap execution. SIGKILL cannot be caught, and traps cannot guarantee cleanup after a crash. Durable recovery needs other safeguards. The first example deliberately preserves the original status even if cleanup fails; the parent must separately verify marker removal. These fixed-name examples assume a fresh private directory without concurrent writers.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Preserve failure during cleanup
bash -c ' (set -C; : > marker.tmp) || exit 1 cleanup() { rc=$? rm -f -- marker.tmp || printf "cleanup failed\n" >&2 printf "cleanup=%s\n" "$rc" exit "$rc" } trap cleanup EXIT exit 7'rc=$?[[ ! -e marker.tmp && ! -L marker.tmp ]] || exit 1printf 'marker gone\n'printf 'child=%s\n' "$rc" Expected stdout:
cleanup=7marker gonechild=7Cleanup removes only the owned marker in the fresh fixture. The explicit exit preserves the incoming status.
Handle TERM in a child
bash -c ' on_term() { printf "TERM\n"; exit 143; } on_exit() { printf "EXIT=%s\n" "$?"; } trap on_term TERM trap on_exit EXIT kill -TERM "$$" printf "unreachable\n"'printf 'child=%s\n' "$?" Expected stdout:
TERMEXIT=143child=143The TERM handler chooses to exit, so the EXIT handler follows. The outer shell continues.
Handle INT in a child
bash -c ' on_int() { printf "INT\n"; exit 130; } trap on_int INT kill -INT "$$" printf "unreachable\n"'printf 'child=%s\n' "$?" Expected stdout:
INTchild=130This is a self-signal experiment, not terminal Ctrl-C or group signal forwarding.
Common mistakes
Do not use an unchecked path in cleanup or send signals to broad process groups. Avoid a cleanup function that exits zero regardless of original failure. Register cleanup only after successfully creating or taking ownership of the resource.
Practice
In a fresh private directory, create one owned marker file and register an EXIT handler. Test success and exit 7; assert the marker is removed and the original exit status survives. Do not signal unrelated processes.
Next: DEBUG and RETURN traps