Identifying received signal name in Bash

(If you only have the number of a signal and want the name, kill -l $SIGNAL_NUM prints the name of a signal; you can avoid that by using the signal names instead of numbers in your call to trap as below.)

This answer says that there’s no way to access the signal name, but if you have a separate function for each signal that you trap, then you already know the signal name:

trap 'echo trapped the HUP signal' HUP
trap 'echo different trap for the INT signal' INT

In many cases, that may be sufficient, but another answer on that same question uses that fact to provide a workaround to fake the behavior you want. It takes a function and a list of signals and sets a separate trap for each signal on that function called with the signal name, so internally it’s actually a separate function for each signal but it looks like a single trap on a single function that gets the signal name as an argument:

Code:

#!/bin/bash

trap_with_arg() {
    func="$1" ; shift
    for sig ; do
        trap "$func $sig" "$sig"
    done
}

func_trap() {
    echo "Trapped: $1"
}

trap_with_arg func_trap INT TERM EXIT

echo "Send signals to PID $$ and type [enter] when done."
read # Wait so the script doesn't exit.

If I run that, then I can send signals to the process and I get output like

Trapped: INT
Trapped: TERM
Trapped: EXIT

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)