#!/bin/bash
#
# --[ signals
#
# Each system has a list of available signasl, but some are standard.
# See: man 7 signal (scroll down for signal names and values)
# See: trap -l or kill -l
#
# By default the shell traps some signals:
# An interactive Bash shell ignores SIGTERM and SIGQUIT.
# SIGINT is caught and handled.
# If job control is active, SIGTTIN, SIGTTOU and SIGTSTP are also ignored.
# SIGHUP exits a shell.
# Some of these behaviors can be modified through shopt.
#
# SIGKILL and SIGSTOP can not be caught, blocked or ignored.
#
# Some signals can be send from the keyboard:
#    SIGINT: Interrupt signal, CTRL-C
#    SIGTSTP: Suspend signal, CTRL-Z
#
# Using the kill command sends an arbitrary signal.
#
# --[ trap
#
# The 'trap' statement allows you to catch a signal and execute some
# commands.
# Syntax:
#              trap COMMANDS SIGNALS
#
# The list of signals can be specified w/ or w/o the SIG prefix, and also
# as numbers.
# There are some special cases and options that we will skip.
#
#
# Example: catching exit

trap "echo exit 0 detected (useful to clean up)" EXIT        # or 0
echo "hello, world"
exit 0

# Example: capturing SIGINT (CTRL-C)

trap "echo SIGINT detected" SIGINT
echo "PID is $$"
i=0
while (( i < 100 ))
do
     echo "iteration $i. Going to sleep"
     sleep 5
     ((i++))
done
exit 0

# Example: trapping SIGKILL

trap "echo you cannot kill me" SIGKILL SIGTSTP
trap "{ touch die.log ; exit; }" SIGTERM
echo "PID is $$. Try to kill me!"
while true; do : done    # ':' is the null (do nothing) command


# Disabling signals
#
# trap '' SIGNAL (two adjacent apostrophes) disables SIGNAL for the
# remainder of the script.
# trap SIGNAL (no apostrophes) restores SIGNAL.
# This is useful to prevent a critical section of the script from an
# undesirable interrupt.


