Mike Conigliaro

How to ensure that only one instance of a script can run at a time

Whenever someone asks for a quick way to ensure that only one instance of a script can run at a time, I see a lot of people giving advice involving temporary lock/PID files (see here, here, and here). This is probably fine for most purposes, but I wonder why more people don’t just check the process table:

SCRIPT_NAME=`basename $0`
if [ `pgrep -c ${SCRIPT_NAME}` -gt 1 ]
then
  echo "Error: An instance of this script is already running!"
  exit 1
fi

This fragment uses pgrep to count the number of running processes with the same name as the currently running script. If the number of these processes is greater than one (the current script will always be counted), then we know that another instance is already running.

As far as I know (and I hope someone will correct me if I’m wrong), this technique avoids the race conditions associated with lock/PID files. It also avoids the possibility of orphaned lock/PID files in the event that your script doesn’t complete and is unable to clean up after itself.

blog comments powered by Disqus