Is it possible to detect *which* trap signal in bash?

Wolf picture Wolf · Feb 1, 2010 · Viewed 12.1k times · Source

Possible Duplicate:
Identifying received signal name in bash shell script

When using something like trap func_trap INT TERM EXIT with:

func_trap () {
    ...some commands...
}

Is there a way in the function block to detect which trap has called it?

Something like:

func_trap () {
    if signal = INT; then
        # do this
    else
        # do that
    fi
}

Or do I need to write a separate function for each trap type that does something different? Is there a bash variable that holds the latest received signal?

Thanks in advance!

Answer

camh picture camh · Feb 2, 2010

You can implement your own trap function that automatically passes the signal to the function:

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

$ trap_with_arg func_trap INT TERM EXIT

The first argument to func_trap will be the name of the signal.