Pejman Moghadam / Scripts

Signal handling in bash scipts

Public domain


#!/bin/bash
# This example comes from: http://www.linuxquestions.org/questions/programming-9/signal-handling-from-bash-257157/

on_die()
{
    # print message
    #
    echo "Dying..."

    # Need to exit the script explicitly when done.
    # Otherwise the script would live on, until system
    # realy goes down, and KILL signals are send.
    #
    exit 0
}


# Execute function on_die() receiving TERM signal
#
trap 'on_die' TERM

# Loop forever, reporting life each second
#
SEC=0
while true ; do
    sleep 1
    SEC=$((SEC+1))
    echo "I'm PID# $$, and I'm alive for $SEC seconds now!"
done

# We never get here.
exit 0

BY: Pejman Moghadam
TAG: bash-script, bash, trap
DATE: 2011-09-04 15:26:14


Pejman Moghadam / Scripts [ TXT ]