2

Let's say I have the following trap, which catches some signals, which terminate the script:

#!/bin/sh
trapterm() {
    echo "Process (PID: $$) interrupted." >&2
    exit 2
}

# add trap to catch terminating signals
trap trapterm INT TERM
# […]

Now, how can I get the signal, which caused the trap being called, and output it? The result should work like this fictitious $SIGNAL:

#!/bin/sh
trapterm() {
    echo "Process (PID: $$) interrupted by signal $SIGNAL." >&2
    exit 2
}

# add trap to catch terminating signals
trap trapterm INT TERM
# […]

Shell-specific solutions (bash) are okay, but I'd prefer a POSIX-compatible ones.

3

As man 1p trap claims that the action (the first argument to trap) is simply evaled without further information about the signal recieved a portable solution might be to install different handlers for each signal:

#!/bin/sh
trap_sig() {
    echo "Process (PID: $$) interrupted by signal $1." >&2
    exit 2
}

# add trap to catch terminating signals
trap 'trap_sig INT' INT
trap 'trap_sig TERM' TERM
# […]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.