Stop trap handlers from swallowing your exit codes

Shell Scripting & Automation

Stop trap handlers from swallowing your exit codes

Technical Briefing | 10/20/2026

You spend hours writing a clean automation script, wrap it in a tidy trap block to handle cleanup, and then realize your script is reporting success even when the primary task crashed hard. It is a classic trap that I have seen bite plenty of senior engineers. When you use trap to clean up temporary files on exit, you are inadvertently masking the actual exit status of your pipeline if you are not careful with how you handle shell variables.

Why the status gets buried

The shell sets the special variable $? to the exit status of the very last command executed. If your trap function runs commands like rm or loggers before you check your own exit code, you have already overwritten the state you needed to capture. Most people write their trap as a simple shell function and forget that the environment is shared across the entire subshell or execution block.

cleanup() { rm -f /tmp/data.tmp; }; trap cleanup EXIT; do_something_risky; status=$?; [ $status -ne 0 ] && exit $status

  • Capture the status into a local variable immediately after the command runs
  • Avoid using commands inside your trap that might touch global variables
  • Remember that the EXIT signal triggers regardless of success or failure

If you really want to be safe, stop relying on implicit exit codes and explicitly pass the result to your cleanup routine. Just checking $? at the very end of your script is often too late if the cleanup function performs its own operations that reset the return code. Keep your trap logic focused only on environmental state, not on decision-making.

Linux Admin Automation  |  © www.ngelinux.com  |  10/20/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted