joe
joe

Reputation: 35087

How can a bash script ensure that not more than one copy of it is running?

How can a bash script ensure that not more than one copy of it is running?

I have tried:

ps -ef| grep /user/loca/shell/sh | wc -l

This shows me 2 because of the grep command. Change it to:

ps -ef | grep /user/loca/shell/sh | grep -v 'grep' wc -l 

then its shows 1. However, if I then vim /user/loca/shell/sh and then execute:

ps -ef| grep /user/loca/shell/sh | grep -v 'grep' wc -l

that shows 2. But there is only one process, I have started.

How can the bash script check whether the process is running?

Upvotes: 3

Views: 376

Answers (3)

Dean Serenevy
Dean Serenevy

Reputation: 1294

I use a file lock:

MY_LOCK_FILE='whatever.lock'

( if (flock -nx 200); then
      # Do stuff here...
  fi
) 200>"$MY_LOCK_FILE"

Upvotes: 0

holygeek
holygeek

Reputation: 16185

Try pgrep instead of 'ps -ef ...' in your script:

pgrep /usr/loca/shell/sh

If that won't work then I'd resort to locking by attempting to create a symbolic link from the script if one does not exist yet and bail out if it already exists, and deleting it upon exit. Creating symbolic link is an atomic operation on unix that can be used as sort of a poorman's lock for shell scripts.

Upvotes: 0

Julian
Julian

Reputation: 2061

The idiom often used in Unix Daemons is to create a file with the PID in it when they start.

Then you can check the existence and/or content of the file when you start, if it's there, you exit and leave that instance running.

At the end of the script you delete the file, ready to run next time.

The only problem comes when the script runs, but does not complete for some reason, leaving the PID file in existence. This can be taken care of by checking its timestamp, if it's too long ago, you assume that it was an aborted run and continue with the current one.

Upvotes: 7

Related Questions