multiple bash traps for the same signal

后端 未结 12 793
悲哀的现实
悲哀的现实 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:38

    Simple ways to do it

    1. If all the signal handling functions are know at the same time, then the following is sufficient (has said by Jonathan):
    trap 'handler1;handler2;handler3' EXIT
    
    1. Else, if there is existing handler(s) that should stay, then new handlers can easily be added like this:
    trap "$( trap -p EXIT | cut -f2 -d \' );newHandler" EXIT
    
    1. If you don't know if there is existing handlers but want to keep them in this case, do the following:
     handlers="$( trap -p EXIT | cut -f2 -d \' )"
     trap "${handlers}${handlers:+;}newHandler" EXIT
    
    1. It can be factorized in a function like that:
    trap-add() {
        local sig="${2:?Signal required}"
        hdls="$( trap -p ${sig} | cut -f2 -d \' )";
        trap "${hdls}${hdls:+;}${1:?Handler required}" "${sig}"
    }
    
    export -f trap-add
    

    Usage:

    trap-add 'echo "Bye bye"' EXIT
    trap-add 'echo "See you next time"' EXIT
    

    Remark : This works only has long as the handlers are function names, or simple instructions that did not contains any simple cote (simple cotes conflicts with cut -f2 -d \').

提交回复
热议问题