# Integration: traps for cleanup and signals sent by the script itself. tmp=work.$$ trap 'rm -f "$tmp"; echo "cleaned up"' EXIT : >"$tmp" [ -f "$tmp" ] && echo "temp file exists" trap 'echo "got USR1"' USR1 kill -USR1 $$ echo "after USR1" trap 'echo "got TERM"' TERM (kill -TERM $$; :) # sent from a subshell to the main shell echo "after TERM: traps run between commands" ( trap 'echo "sub HUP"; exit 4' HUP; sh -c 'kill -HUP $PPID'; echo not-reached ); echo "status $?" ( trap 'echo "child INT"; exit 5' INT; sh -c 'kill -INT $PPID'; echo not-reached ); echo "child status $?" ( trap 'echo "trap in subshell"' USR1; sh -c 'kill -USR1 $PPID'; echo "subshell continues" ) trap '' USR1; kill -USR1 $$; echo "ignored USR1" trap 'echo "trap sees status $?"' USR2 false; kill -USR2 $$ echo "end"