bashbash-trap

Multiple Bash traps for the same signal


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 fire for the same signal?


Solution

  • Edit:

    It appears that I misread the question. The answer is simple:

    handler1 () { do_something; }
    handler2 () { do_something_else; }
    handler3 () { handler1; handler2; }
    
    trap handler3 SIGNAL1 SIGNAL2 ...
    

    Original:

    Just list multiple signals at the end of the command:

    trap function-name SIGNAL1 SIGNAL2 SIGNAL3 ...
    

    You can find the function associated with a particular signal using trap -p:

    trap -p SIGINT
    

    Note that it lists each signal separately even if they're handled by the same function.

    You can add an additional signal given a known one by doing this:

    eval "$(trap -p SIGUSR1) SIGUSR2"
    

    This works even if there are other additional signals being processed by the same function. In other words, let's say a function was already handling three signals - you could add two more just by referring to one existing one and appending two more (where only one is shown above just inside the closing quotes).

    If you're using Bash >= 3.2, you can do something like this to extract the function given a signal. Note that it's not completely robust because other single quotes could appear.

    [[ $(trap -p SIGUSR1) =~ trap\ --\ \'([^\047]*)\'.* ]]
    function_name=${BASH_REMATCH[1]}
    

    Then you could rebuild your trap command from scratch if you needed to using the function name, etc.