multiple bash traps for the same signal

后端 未结 12 788
悲哀的现实
悲哀的现实 2020-12-13 01:47

When I use the trap command in bash, the previous trap for the given signal is replaced.

Is there a way of making more than one trap<

12条回答
  •  自闭症患者
    2020-12-13 02:32

    A special case of Richard Hansen's answer (great idea). I usually need it for EXIT traps. In such case:

    extract_trap_cmd() { printf '%s\n' "${3-}"; }
    get_exit_trap_cmd() {
        eval "extract_trap_cmd $(trap -p EXIT)"
    }
    
    ...
    trap "echo '1  2'; $(get_exit_trap_cmd)" EXIT
    ...
    trap "echo '3  4'; $(get_exit_trap_cmd)" EXIT
    

    Or this way, if you will:

    add_exit_trap_handler() {
        trap "$1; $(get_exit_trap_cmd)" EXIT
    }
    ...
    add_exit_trap_handler "echo '5  6'"
    ...
    add_exit_trap_handler "echo '7  8'"
    

提交回复
热议问题