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?
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?
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: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
ortrap -p 2
to print the trap for a specific signal.I have been wrote a set of functions for myself to a bit resolve this task in a convenient way.
traplib.sh
test.sh
Usage
Output
Edit:
It appears that I misread the question. The answer is simple:
Original:
Just list multiple signals at the end of the command:
You can find the function associated with a particular signal using
trap -p
: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:
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.
Then you could rebuild your trap command from scratch if you needed to using the function name, etc.