Bash and Trap

Extremely useful in scripting. For a full listing of signals, use kill -l. Here’s a sample script:

# Sample script to test the trap command

# Catch and report errors
error_keyboard_interrupt() {
      echo -e "Caught SIGINT; logging and exiting"
      TEMPLOG=$(mktemp XXXXXX)

      echo -e "$1 Caught keyboard interrupt!" > $TEMPLOG
      mail -s "Severe" < $TEMPLOG

      rm -f $TEMPLOG

TESTPARAM="Oh noes!"
trap $(error_keyboard_interrupt $TESTPARAM) SIGINT

while :  # Same as while true
      sleep 60
      echo -e "Still alive..."