Handling multiple signals with one trap in bash

There is a question about multiple bash hooks for the same signal . How about the opposite version? You can 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

      

+3


source to share


1 answer


You will need to write a 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 can write a custom function to set all the hooks for you. Then you will call the function with all the signals you want to handle:_trap [sig1] [sig2] ...

handle_sig () {
  case "$1" in
    HUP)
      echo "CATCH: SIGHUP"
      ;;
    INT)
      echo "CATCH: SIGINIT"
      ;;
    *)
      echo "CATCH: SIG$1"
      ;;
  esac
}

_trap () {
  for sig in "$@"
  do
    trap "handle_sig $sig" "$sig"
  done
}

_trap INT HUP USR1

      

+4


source







All Articles