multiple bash traps for the same signal

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

    There's no way to have multiple handlers for the same trap, but the same handler can do multiple things.

    The one thing I don't like in the various other answers doing the same thing is the use of string manipulation to get at the current trap function. There are two easy ways of doing this: arrays and arguments. Arguments is the most reliable one, but I'll show arrays first.

    Arrays

    When using arrays, you rely on the fact that trap -p SIGNAL returns trap -- ??? SIGNAL, so whatever is the value of ???, there are three more words in the array.

    Therefore you can do this:

    declare -a trapDecl
    trapDecl=($(trap -p SIGNAL))
    currentHandler="${trapDecl[@]:2:${#trapDecl[@]} - 3}"
    eval "trap -- 'your handler;'${currentHandler} SIGNAL"
    

    So let's explain this. First, variable trapDecl is declared as an array. If you do this inside a function, it will also be local, which is convenient.

    Next we assign the output of trap -p SIGNAL to the array. To give an example, let's say you are running this after having sourced osht (unit testing for shell), and that the signal is EXIT. The output of trap -p EXIT will be trap -- '_osht_cleanup' EXIT, so the trapDecl assignment will be substituted like this:

    trapDecl=(trap -- '_osht_cleanup' EXIT)
    

    The parenthesis there are normal array assignment, so trapDecl becomes an array with four elements: trap, --, '_osht_cleanup' and EXIT.

    Next we extract the current handler -- that could be inlined in the next line, but for explanation's sake I assigned it to a variable first. Simplifying that line, I'm doing this: currentHandler="${array[@]:offset:length}", which is the syntax used by Bash to say pick length elements starting at element offset. Since it starts counting from 0, number 2 will be '_osht_cleanup'. Next, ${#trapDecl[@]} is the number of elements inside trapDecl, which will be 4 in the example. You subtract 3 because there are three elements you don't want: trap, -- and EXIT. I don't need to use $(...) around that expression because arithmetic expansion is already performed on the offset and length arguments.

    The final line performs an eval, which is used so that the shell will interpret the quoting from the output of trap. If we do parameter substitution on that line, it expands to the following in the example:

    eval "trap -- 'your handler;''_osht_cleanup' EXIT"
    

    Do not be confused by the double quote in the middle (''). Bash simply concatenates two quotes strings if they are next to each other. For example, '1'"2"'3''4' is expanded to 1234 by Bash. Or, to give a more interesting example, 1" "2 is the same thing as "1 2". So eval takes that string and evaluates it, which is equivalent to executing this:

    trap -- 'your handler;''_osht_cleanup' EXIT
    

    And that will handle the quoting correctly, turning everything between -- and EXIT into a single parameter.

    To give a more complex example, I'm prepending a directory clean up to the osht handler, so my EXIT signal now has this:

    trap -- 'rm -fr '\''/var/folders/7d/qthcbjz950775d6vn927lxwh0000gn/T/tmp.CmOubiwq'\'';_osht_cleanup' EXIT
    

    If you assign that to trapDecl, it will have size 6 because of the spaces on the handler. That is, 'rm is one element, and so is -fr, instead of 'rm -fr ...' being a single element.

    But currentHandler will get all three elements (6 - 3 = 3), and the quoting will work out when eval is run.

    Arguments

    Arguments just skips all the array handling part and uses eval up front to get the quoting right. The downside is that you replace the positional arguments on bash, so this is best done from a function. This is the code, though:

    eval "set -- $(trap -p SIGNAL)"
    trap -- "your handler${3:+;}${3}" SIGNAL
    

    The first line will set the positional arguments to the output of trap -p SIGNAL. Using the example from the Arrays section, $1 will be trap, $2 will be --, $3 will be _osht_cleanup (no quotes!), and $4 will be EXIT.

    The next line is pretty straightforward, except for ${3:+;}. The ${X:+Y} syntax means "output Y if the variable X is unset or null". So it expands to ; if $3 is set, or nothing otherwise (if there was no previous handler for SIGNAL).

提交回复
热议问题