trap "<new trap action>; $(get_old_trap SIGNAL)" SIGNAL

From: Michael Wang (mwang_at_unixlabplus.com)
Date: 02/15/05


Date: Tue, 15 Feb 2005 12:49:26 GMT

I want to be able to add new trap to existing trap by saying:

trap "<new trap action>; $(get_old_trap SIGNAL)" SIGNAL

Please comment if the following function get_old_trap()
covers all cases. This only works with ksh93, and that is ok
for me. This is because:

(1) bash as of the current release (v3.0) is not POSIX compliant as
demonstrated by:

--
trap 'echo a' exit
a=$(trap)
echo $a
/* no output */
--
POSIX requires that the old trap is saved in $a.
(2) while ksh88 saves the trap, it does not in a function:
--
$ /bin/ksh # Version M-11/16/88i
$ trap 'echo a' exit
$ a=$(trap)
$ echo $a
trap -- 'echo a' EXIT
$ a() { trap; }
$ a
--
Thanks.
get_old_trap() {
  typeset line signal="$1" old_trap=/tmp/$$.$RANDOM
  trap > $old_trap
  exec 3< $old_trap
  rm $old_trap
  while read -u3 -r -- line; do
    [[ "$line" == *?(SIG)$signal ]] || continue
    line=${line#trap --+( )}
    eval line=${line%+( )?(SIG)$signal}
    printf "%s\n" "$line"
    return 0
  done
  return 1
}
trap "echo trap1" EXIT
trap "echo trap2; $(get_old_trap EXIT)" EXIT
-- 
For low fair air travel, take Independence Air - http://www.flyi.com/.
Michael Wang * http://www.unixlabplus.com/ * mwang@unixlabplus.com


Relevant Pages