Be careful not to clobber existing traps

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the bash category.

Last Updated: 2024-11-23

The trap command replaces traps if already present. Therefore you should be exceedingly careful workign with legacy code in case you remove important trap handlers.

In case you do actually want both present and new to be executed, I suppose you can hack around a bit:

function overtrap {
  trap="$1"
  sig=$(echo $2 | tr [a-z] [A-Z])
  cur="$(trap -p $sig | sed -nr "s/trap -- '(.*)' $sig\$/\1/p")"
  if test ${cur:+x}; then
    trap "{ $trap; }; $cur" $sig
  else
    trap "$trap" $sig
  fi
}

overtrap 'echo hi' exit
overtrap 'echo ho' exit

# hi
# ho

Resources