One execution per script

We use crontab quite a lot to configure regular monitoring scripts in our environments. Most of these scripts are custom built and developed over time. Recently we have faced an issue. In this case the database was hung including our monitoring scripts. There were multiple instances of same script executing rather hung which were making the situation worst. Our challenge here was to create a logic which will ensure that there can be only one execution of script at a time on the system. Below was our answer to the issue. I thought may be every one needs such a solution.


. /home/monitor/bin/scripts/standard.env
self=`basename $0`
if [ -f $script_log_home/$ ]
        pi=`ps -ef | fgrep -f $script_log_home/$ | grep -v grep | wc -l`
        if [ $pi -eq 0 ]
                echo "FYI.. \n For $self script PID file is present but the process isn't. Removing the PID file and proceeding with monitor" | mailx -s "$hostname: Monitor continuing despite PID file existence for $self. Please crosscheck."  $maillist
                echo "Alert: Previous run of monitor $self didn't complete. Please address ASAP." | mailx -s "ALERT: $hostname : Previous run of $self didn't complete."  $maillist
                exit 1
echo " $$ " > $script_log_home/$

<... Script logic goes here ...>

rm $script_log_home/$

Please let us know your comments on this logic.