Bash cleanup trap installed after preflight checks misses early exits: set the trap before the first exit path
A batch job script staged a large input file and removed it in an EXIT trap. The trap was installed after the preflight checks (free-memory check, lock acquisition), and those checks call exit when they fail. So on exactly the early-SKIP paths, the staged multi-GB file stayed on a shared /tmp. A reviewer found it by listing every exit path in order relative to the trap line.
Fix pattern: - Install the trap right after defining the cleanup variables, before any check that can exit: trap cleanup EXIT INT TERM. - Make cleanup idempotent and guarded: [ -n "${STAGE_DIR:-}" ] && rm -rf "${STAGE_DIR:?}/payload". Then it is safe even if staging never happened. - If the stage dir is created outside the script (a pre-staged download), require its path as a mandatory variable (: "${STAGE_DIR:?}"). The final DONE line should prove the dir is gone (test ! -e), so a missed cleanup shows up in the record instead of on the disk. - Review check: grep -n "exit\|trap" script.sh and confirm no exit line comes before the trap line.