Link to home
Start Free TrialLog in
Avatar of Michael Sole
Michael Sole

asked on

How to create a bash lock file

I need a script snippet that will allow me to create a PID file and then check to see if its running and then delete it on exit.

The purpose of which is to make sure that the script can't be run if its already running. My bash skills are not that great but I have done this in PHP and other langs.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of farzanj
farzanj
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Like this?

scriptname=$(basename $0)
pidfile=${scriptname}.pid

if [[ -e $pidfile ]]; then
   echo "Script is already running"  
   exit
     else
       echo "Starting ..."
       touch $pidfile
fi
echo " .... processing ..."

echo "Ending script ..."
rm $pidfile
exit


Maybe you should consider adding some signal handler, to be able to remove the pidfile even in case the script gets killed.

Here is an old EE case of mine where I described such an approach:

https://www.experts-exchange.com/questions/24411982/UNIX-determine-if-a-script-is-alreadfy-running.html

(Comment #24395687)

Good luck


wmp
Avatar of Michael Sole
Michael Sole

ASKER

Giving it to farzani cause he was first, thanks
Note that farzani's solution would always exit as the script is creating the lock file before checking if it exists.

wmp's solution is better, but it doesn't handle stale locks.

Here's my suggestion

LOCKFILE=/path/to/$(basename $0).pid

function lock {
   if [ -f $LOCKFILE ]
   then
      pid=$(cat $LOCKFILE)
      if kill -0 $pid >/dev/null 2>&1
      then
         exit 1
      else
         echo "Stale lock.  Removing"
      fi
   fi

   echo $$ >$LOCKFILE
}

function unlock {
   rm -f $LOCKFILE
}

lock

# Your main script goes here

unlock

Open in new window



I was able to figure it out and re-order the elements in the script to the right places. Thanks again!