Reputation: 8052
There is question about multiple bash traps for same signal. What about the opposite version? Is possible to write something like this:
sighand () {
case $1 in
1)
echo "CATCH: SIGHUP"
;;
2)
echo "CATCH: SIGINIT"
;;
...
# ALL EXCEPT 9
...
esac
};
trap sighand ALL
instead of this:
sighand () {
echo "CATCH: TERM"
};
trap sighand TERM
Upvotes: 3
Views: 5526
Reputation: 47
Handling multiple signals with one trap in bash :
trap '' 2 3 6 15 18 20
Only Close Terminal Window will work in this case to Quit the Script.
This one liner is taken from my open source project called Automated_Quiz, which is hosted here : https://sourceforge.net/projects/automated-quiz/
Also check : https://www.computerhope.com/unix/signals.htm
Upvotes: 0
Reputation: 1
This answer should do it: Identifying received signal name in Bash. I've used it for a similar reason. A minor extention to @Leistungsabfall's above. This amendment adds the ability to specify a function to use in the trap by name. Example here:
trap_with_arg() {
func="$1" ; shift
for sig ; do
trap "$func $sig" "$sig"
done
}
function handler() {
local SIGNAL=${1}
[ "${DEBUG}" -gt "0" ] && echo "Received Signal: ${SIGNAL}" >&2
case "${SIGNAL}" in
EXIT)
[ "${DEBUG}" -gt "0" ] && echo "EXIT clause"
# ^C
;;
USR2)
[ "${DEBUG}" -gt "0" ] && echo "DUSR2 clause"
;;
HUP|USR1)
[ "${DEBUG}" -gt "0" ] && echo "HUP|USR1 clause"
;;
ABRT)
[ "${DEBUG}" -gt "0" ] && echo "ABRT clause"
;;
INT|TERM)
[ "${DEBUG}" -gt "0" ] && echo "INT|TERM clause"
;;
esac
exit 0
}
trap_with_arg handler USR1 USR2 HUP INT ABRT TERM EXIT
Upvotes: 0
Reputation: 4681
You would have to write separate function for each signal:
handle_hup () {
echo "CATCH: SIGHUP";
}
handle_int () {
echo "CATCH: INT";
}
trap handle_hup HUP
trap handle_int INT
As a workaround you could write a custom function to set all the traps for you. Then you would call the function with all the signals you want to be handled: _trap [sig1] [sig2] ...
handle_sig () {
case "$1" in
HUP)
echo "CATCH: SIGHUP"
;;
INT)
echo "CATCH: SIGINT"
;;
*)
echo "CATCH: SIG$1"
;;
esac
}
_trap () {
for sig in "$@"
do
trap "handle_sig $sig" "$sig"
done
}
_trap INT HUP USR1
Upvotes: 4