Let's say you have a shell script that runs some sort of cleanup codevia an EXIT trap, like this:#!/bin/bashmytrap () {  echo It's a trap! >&2}trap mytrap exitecho I am at the end of the script.This will, as expected, print out It's a trap! when the scriptexits:$ sh myscriptI am at the end of the script.It's a trap!You modify the script to add a function that generates someoutput that ultimately gets piped to another command, like this:#!/bin/bashmytrap () {  echo It's a trap! >&2}myfunc () {  echo I've got a bad feeling about this...}trap mytrap exitmyfunc | cat > /dev/nullecho I am at the end of the script.Because of the pipe, the code in myfunc is run in a subshell...andsubshells don't appear to inherit the trap behavior of the parent,which means if you perform any actions here that should be cleaned upby your trap code that won't happen.So you try this:myfunc () {  trap mytrap EXIT  echo I've got a bad feeling about this...}And it still fails to trigger mytrap when the subshell exits.  Itturns out that you need an explicit exit, like this:myfunc () {  trap mytrap EXIT  echo I've got a bad feeling about this...  exit}With the above code, mytrap will trigger appropriately upon exitfrom the subshell:$ sh myscript It's a trap!I am at the end of the script.It's a trap!Is that expected behavior?  I was surprised by several things here:trap settings weren't inherited by subshellsimplicit exit from a subshell does not appear to trigger an EXITtrap
Trap handling and implicit subshells in shell scripts
shell;trap