multiple bash traps for the same signal

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

    I didn't like having to play with these string manipulations which are confusing at the best of times, so I came up with something like this:

    (obviously you can modify it for other signals)

    exit_trap_command=""
    function cleanup {
        eval "$exit_trap_command"
    }
    trap cleanup EXIT
    
    function add_exit_trap {
        local to_add=$1
        if [[ -z "$exit_trap_command" ]]
        then
            exit_trap_command="$to_add"
        else
            exit_trap_command="$exit_trap_command; $to_add"
        fi
    }
    

提交回复
热议问题