Make a Bash script quit if it detects multiple running instances of itself

Let's say I've got a script called by cron at regular intervals and I want it to exit if it detects that a previously called instance is still running. Placing the following at the top is one way to do it:

#!/bin/bash

if [ "$(pgrep -x $(basename $0))" != "$$" ]; then
 echo "Error: another instance of $(basename $0) is already running"
 exit 1
fi

The way this works is:

  • Bash built-in "$$" returns the PID of its process
  • Bash built-in "$0" returns the name of its process (e.g. /usr/local/bin/script.sh)
  • Command "basename $0" discards the path (e.g. /usr/local/bin/script.sh becomes script.sh)
  • Command "pgrep -x $(basename $0)" searches for PIDs of current script
  • When more than a single instance of the script is running, multiple PIDs will be returned by "pgrep", no longer matching a single PID returned by "$$".

UPDATE 2012-11-22: Improved code to make a Bash script quit if it detects multiple running instances of itself

1 Comment

  • 1. Davel replies at 1st June 2012, 1:28 pm :

    [[ "$(pgrep -x $(basename $0))" != "$$" ]] && exit 1
    

    Seems to work as well, and has the advantage of being a one-liner suitable for macro definition.

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).