bash signal trapping

For the docker we need to try some bash signals, but what are they and how to trap them....

Well trapping a signal is quite easy.

#!/bin/bash
#!/usr/bin/env bash
trap cleanup 1 2 3 6 15

cleanup()
{
  echo "Caught Signal ... cleaning up."
  sleep 1s
  echo "Done  ... quitting."
  exit 1
}

# wait forever
while true
do
  tail -f /dev/null & wait ${!}
done

If you are wondering what the numbers 1 2 3 6 15 are they are explained in this table

Number Name Meaning
0 0 On exit from shell
1 SIGHUP Clean tidyup
2 SIGINT Interrupt
3 SIGQUIT Quit
6 SIGABRT Abort
9 SIGKILL Die Now (cannot be trap'ped)
14 SIGALRM Alarm Clock
15 SIGTERM Terminate

If for some reason you needed to have specific handling then you could do it like this

#!/bin/bash
#!/usr/bin/env bash
trap sig1_2   1 2
trap sig_15   15

sig1_2()
{
   echo "Sig 1 or 2"
}

sig_15()
{
  echo "15"
  rm -Rf / #Only kidding :)
}

Note: Note that if your script was started in an environment which itself was ignoring signals (for example, under nohup control), the script will also ignore those signals.