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 .....