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: 2023-03-28

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 {
  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
    trap "$trap" $sig

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

# hi
# ho