LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Signal handling from bash (https://www.linuxquestions.org/questions/programming-9/signal-handling-from-bash-257157/)

shy 11-20-2004 05:12 AM

Signal handling from bash (SOLVED)
 
Is there any possibility to catch a signal in bash script?
I would like to do something from dying script (when the system starts to reboot).

Hko 11-20-2004 07:52 AM

Re: Signal handling from bash
 
Quote:

Originally posted by shy
Is there any possibility to catch a signal in bash script?
I would like to do something from dying script (when the system starts to reboot).

Yes, that's possible.
What ever you want to do when receiving the TERM signal, make sure you do it quickly.
Code:

#!/bin/bash

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


shy 11-20-2004 08:41 AM

Thank you!


All times are GMT -5. The time now is 11:49 PM.