I'm developing a script which manage some traps. At the beginning I only managed INT and SIGTSTP with this code and it works very well:
#!/bin/bash
function capture_traps() {
echo -e "\nDoing something on exit"
exit 1
}
trap capture_traps INT
trap capture_traps SIGTSTP
read -p "Script do its stuff here and we use read for the example we pause for time to generate trap event"
exit 0
Then I tried to add the new traps I want to manage, which are SIGINT and SIGHUP. In first instance I did this (which is working):
#!/bin/bash
function capture_traps() {
echo -e "\nDoing something on exit"
exit 1
}
trap capture_traps INT
trap capture_traps SIGTSTP
trap capture_traps SIGINT
trap capture_traps SIGHUP
read -p "Script do its stuff here and we use read for the example we pause for time to generate trap event"
exit 0
Then, I decided to do different stuff on exit depending of the trap and I don't want to create different functions for each one. I know in bash you can loop over arguments on a function using for item in $@; do
nomenclature, so I tried, but it seems is not working trying to differentiate the kind of trap. I made this code which is not working.
#!/bin/bash
function capture_traps() {
for item in $@; do
case ${item} in
INT|SIGTSTP)
echo -e "\nDoing something on exit"
;;
SIGINT|SIGHUP)
echo -e "\nDoing another thing even more awesome"
;;
esac
done
exit 1
}
trap capture_traps INT SIGTSTP SIGINT SIGHUP
read -p "Script do its stuff here and we use read for the example we pause for time to generate trap event"
exit 0
Any help? There must be a way to improve my code using only one function for all traps, but I don't know how...