Stop your trap commands from losing their exit context

Shell Scripting & Automation

Stop your trap commands from losing their exit context

Technical Briefing | 8/2/2026

Everyone learns early on that you should use trap to clean up temporary files or kill sub-processes. But most scripts use a basic trap on EXIT that completely ignores whether the script actually succeeded or failed. If you just define a function to clean up, you are throwing away the exit status that the shell could have passed to your handler. This bit me in prod when I was debugging a deployment that kept failing silently because the cleanup task wiped out the logs I actually needed to inspect.

Capturing the exit status without the hacky boilerplate

The shell sets the special variable $? to the return code of the last command, but by the time your trap fires, that variable might already be different if your cleanup logic runs another command. The right way to do this is to explicitly capture the status the moment the script hits a signal or an exit. Don’t rely on the shell state to magically persist across multiple command executions in your handler.

trap 'status=$?; rm -f /tmp/data.$$.tmp; exit $status' EXIT INT TERM

  • Use the status=$? trick to snapshot the exit code before running any other commands in your handler
  • Always trap INT and TERM alongside EXIT so your cleanup actually runs on manual interrupts
  • Avoid using complex logic inside the trap string; keep it to simple function calls or single commands

Once you get into the habit of capturing that status variable, you can even make your cleanup conditional. Maybe you only want to purge those logs if the script finished successfully, but leave them alone if something crashed. Just add an if statement inside your trap function that checks the captured status. It keeps your automation clean and prevents you from hunting for evidence that your own script deleted.

Linux Admin Automation  |  © www.ngelinux.com  |  8/2/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted