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.

Michael SoleDirector of SupportAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

I would call it a lock file.


#To create the file
touch $LOCK_FILE

if [[ -f $LOCK_FILE ]]
     exit 1

#Delete the lock file at the end
rm -f $LOCK_FILE

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Like this?

scriptname=$(basename $0)

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

echo "Ending script ..."
rm $pidfile

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:

(Comment #24395687)

Good luck

Michael SoleDirector of SupportAuthor Commented:
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 ]
      pid=$(cat $LOCKFILE)
      if kill -0 $pid >/dev/null 2>&1
         exit 1
         echo "Stale lock.  Removing"

   echo $$ >$LOCKFILE

function unlock {
   rm -f $LOCKFILE


# Your main script goes here


Open in new window

Michael SoleDirector of SupportAuthor Commented:
I was able to figure it out and re-order the elements in the script to the right places. Thanks again!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.