Home > Uncategorized > One instance at a time with PID file in Bash

One instance at a time with PID file in Bash

Often times, I only want a script to run one instance at a time. For example, if the the script is copying files, or rsync’ing between systems, it can be disastrous to have two instances running concurrently, and this situation is definitely possible if you run the script from cron.

I figured out a simple way to make sure only one instance runs at a time, and it has the added benefit that if the script dies midway through, another instance will start – a drawback of just using lock files without a pid.

Without further ado, here’s my script:

#!/bin/bash
pidfile=/var/run/sync.pid
if [ -e $pidfile ]; then
pid=`cat $pidfile`
if kill -0 &>1 > /dev/null $pid; then
echo "Already running"
exit 1
else
rm $pidfile
fi
fi
echo $$ > $pidfile
 
#do your thing here
 
rm $pidfile
Categories: Uncategorized Tags:
  1. February 16th, 2009 at 18:56 | #1
    Related and probably interesting to you: over at the sysadvent log there’s an article on best lockfile practices.
  2. Gerard Seibert
    November 30th, 2009 at 07:18 | #2
    I modified your script slightly. It works on Bash and does not create a ‘1′ file. Using the ‘f’ flag with ‘rm’ also prevents useless error messages.

    PID_FILE=”/var/run/my_prog.pid”

    ## Check to see if the program is running
    if [[ -e ${PID_FILE} ]]; then
    ## Capture the ‘pid’ number in ‘pid’ variable
    pid=$( ${PID_FILE}

    do something

    ## Remove the pid file if it exists
    if [[ -e ${PID_FILE} ]]; then
    rm -f ${PID_FILE}
    fi

  1. No trackbacks yet.