#!/bin/bash
#
# testpid.sh - demo script to show how to check if a script
# with the same name is currently running
#
# by Leo Eibler
# resources:
#    http://www.eibler.at
#    http://leo.sprossenwanne.at
#    http://www.nullpointer.at
#

# PID - pid of the current script
PID=$$
# SCRIPTNAME - current name of the script without directory prefix
SCRIPTNAME=`basename $0`
# PIDFILE - where to write the current pid
PIDFILE=/tmp/$SCRIPTNAME.pid

# ENDEXECUTION - if 1 then stop script, if 0 everything is ok and continue
ENDEXECUTION=0

if [ -f "$PIDFILE" ]
then
    RUNNINGPID=`cat "$PIDFILE"`
    echo "got pid from $RUNNINGPID from pidfile '$PIDFILE'"
    PROGRAMPID=`ps -e | grep "$SCRIPTNAME" | grep -v grep | awk '{print $1;}'`
    for PIDEL in $PROGRAMPID
    do
        echo "testing pid of running scripts '$PIDEL' == '$RUNNINGPID' from pidfile"
        if [ "$PIDEL" == "$RUNNINGPID" ]
        then
            echo "found PID $RUNNINGPID current running - end execution"
            ENDEXECUTION=1
            break
        fi
    done
fi

if [ "$ENDEXECUTION" == "1" ]
then
    echo "Current script '$SCRIPTNAME' already running (pid $RUNNINGPID) - end execution"
    exit 1
fi
# writing PID to pidfile
echo $PID > $PIDFILE

#
# ---- START ----
#

echo "do your stuff here ..."
sleep 5
echo "... end script"

#
# ---- END ----
#

# delete pidfile
rm $PIDFILE
exit 0
