bash : Signal Handling

A script could have lock file or is producing temporary files which need to be renamed before exiting. What if the script receives a signal and quits in the middle leaving temporary files scattered around? Bash provides “trap” function to trap a signal and right a signal handler.

if [ ! -e $lockfile ]; then
        # Arm the handler
        trap "rm -f $lockfile; exit" INT TERM EXIT
        touch $lockfile
        critical-section
        rm $lockfile
        # Disarm the handler
        trap - INT TERM EXIT
fi

Or you can write a function like below.

Handle_Exit_Safely()
{
        rm -f $lockfile
        exit
}
if [ ! -e $lockfile ]; then
        # Arm the handler
        trap Handle_Exit_Safely INT TERM EXIT
        touch $lockfile
        critical-section
        rm $lockfile
        # Disarm the handler
        trap - INT TERM EXIT
fi