Stop trap handlers from biting you when a subshell goes sideways

Shell Scripting & Automation

Stop trap handlers from biting you when a subshell goes sideways

Technical Briefing | 11/17/2026

You spend hours writing a clean script with proper error handling, only to realize your trap cleanup function never runs because the script died inside a pipe or a background subshell. Most tutorials suggest a generic trap EXIT and call it a day. But that rarely holds up once you start nesting functions or piping data between processes. This bit me in prod when a cleanup function failed to unmount a loop device because the script didn’t realize it was dying in a child context.

Why your trap is lying to you

The shell manages traps per process, not per pipe segment. When you run something like cmd1 | cmd2, both commands end up in subshells. If one crashes, your main script keeps chugging along, or worse, the exit status is ignored. You need to explicitly set the pipefail option and ensure your trap handles the state of the parent process correctly, otherwise you are just pretending to be resilient.

set -o pipefail
trap 'rm -f "$TEMP_FILE"; exit' EXIT INT TERM
(cat data | process_script) > output.log

  • Always enable pipefail or your error codes will vanish into the abyss
  • Export the trap handler function so child shells have a ghost of a chance to execute it
  • Check SHLVL if you really need to differentiate between the main process and subshells

The right approach is to treat subshells as independent failure points. If you are doing something dangerous, put the trap logic in a separate file and source it, or just use a temporary directory that you clean up with a cron job if the script crashes hard enough to skip the trap entirely. Keep your cleanup logic idempotent, because the day will come when it runs on a half-written file and you’ll be glad it didn’t choke.

Linux Admin Automation  |  © www.ngelinux.com  |  11/17/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted