multiple bash traps for the same signal

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

    I add a slightly more robust version of Laurent Simon's trap-add script:

    • Allows using arbitrary commands as trap, including such with ' characters
    • Works only in bash; It could be rewritten with sed instead of bash pattern substitution, but that would make it significantly slower.
    • Still suffers from causing unwanted inheritance of the traps in subshells.

    trap-add () {
        local handler=$(trap -p "$2")
        handler=${handler/trap -- \'/}    # /- Strip `trap '...' SIGNAL` -> ...
        handler=${handler%\'*}            # \-
        handler=${handler//\'\\\'\'/\'}   # <- Unquote quoted quotes ('\'')
        trap "${handler} $1;" "$2"
    }
    

提交回复
热议问题