multiple bash traps for the same signal

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

    No

    About the best you could do is run multiple commands from a single trap for a given signal, but you cannot have multiple concurrent traps for a single signal. For example:

    $ trap "rm -f /tmp/xyz; exit 1" 2
    $ trap
    trap -- 'rm -f /tmp/xyz; exit 1' INT
    $ trap 2
    $ trap
    $
    

    The first line sets a trap on signal 2 (SIGINT). The second line prints the current traps — you would have to capture the standard output from this and parse it for the signal you want. Then, you can add your code to what was already there — noting that the prior code will most probably include an 'exit' operation. The third invocation of trap clears the trap on 2/INT. The last one shows that there are no traps outstanding.

    You can also use trap -p INT or trap -p 2 to print the trap for a specific signal.

提交回复
热议问题