Run only one instance of a bash shell script

Say you write a shell script and want ensure that only one instance of your script is running.  This is handy if, for instance, you are going to run your script via cron every X minutes and it is possible that your script may take longer than X minutes to run.

To accomplish this, just prepend the boilerplate code below at the start of your script.  It use an operating system lock via the flock tool to ensure that only one instance is running; by checking with flock instead of just checking for the existence of a lock file, we ensure the lock is released as soon as your script completes - even if your script crashes and fails to remove the lock file.  Also note that I follow all Filesystem Hierarchy Standards (FHS) for location, name, and contents of the lock file.  The script requires the existence of bash, flock, basename, and awk command-line tools, which are pretty ubiquitous at least on Linux these days.  Enjoy!

#!/bin/bash

# Obtain a lock for this instance
#
lockdir=/tmp
if [ -w /var/lock ]; then lockdir=/var/lock ; fi
self=`basename $0`
pidf="$lockdir/LCK..$self.uid$EUID.pid"
exec 221>${pidf}
flock --exclusive --nonblock 221 ||
{
        echo "Already running"
        exit 1
}
echo $$ | awk '{printf "%10u\n",$0}' >&221
#

# Lock obtained, will be released automatically on exit.
#
# ... Now do whatever you want here .....

4 comments:

Bet Bhai said...

Fairplay Cricket Live is an online platform designed for cricket fans who enjoy live betting and real-time match action. It offers users the chance to place bets on their favorite teams, players, and match events while watching the game unfold. Whether it is an international match, a T20 league, or a domestic tournament, Fairplay Cricket Live gives users access to multiple betting options in one place.
fairplay cricket live

Goldbet said...

You receive a secure online cricket betting ID that allows access to cricket exchange live markets, IPL betting apps, and other sports.For example, during a tight IPL chase, odds can shift every over. Goldbet App

Silverexchange said...

Cricket betting platforms should provide fast updates during live matches. While exploring Silver Exchange, I noticed the markets refresh quickly and the interface feels smooth.

fairplay said...

A smooth interface strengthens online engagement. Fairplay Club operates with reliability.