Bash Lockfile Script

Just a little lockfile library for bash.
If the lockfile script is in the same folder as your script.. source $(dirname $0)/lockfile.sh

Then call.

setup_lockfile
check_lock
create_lock

Do your scripty stuff then call

cleanup_lock

#!/bin/bash
# Lockfile utilities
setup_lockfile(){
 # set name of this program's lockfile:
 MY_NAME=`basename $0`
 LOCKFILE=/tmp/lock.${MY_NAME}
 # MAX_AGE is how long to wait until we assume a lock file is defunct
 # scary stuff, with loads of scope for improvement...
 # could use fuser and see if there is a process attached/not?
 # maybe check with lsof? or just bail out?
 MAX_AGE=120
 echo "My lockfile name is ${LOCKFILE}"

# Wait a random time up to half an hour before starting
 echo "Random wait"
 sleep $[ ( $RANDOM % 1800 ) + 1 ]s
}

check_lock(){
 # Check for an existing lock file
 while [ -f /tmp/lock.${MY_NAME}* ]
 do
 # A lock file is present
 if [[ `find /tmp/lock.* -mmin +${MAX_AGE}` > "0" ]]; then
 echo "WARNING: found and removing old lock file...`ls /tmp/lock.${MY_NAME}*`"
 rm -f /tmp/lock.${MY_NAME}*
 else
 echo "A recent lock file already exists : `ls /tmp/lock.${MY_NAME}* | awk -F. {'print $2"."$3", with PID: " $4'}`"
 echo "Will wait until the lock file is over ${MAX_AGE} minutes old then remove it..."
 fi
 sleep $(( 60 + (( RANDOM % 10 ))))
 done
}

create_lock(){
 # ok to carry on... create a lock file - quickly ;-)
 touch ${LOCKFILE}
 # check we managed to make it ok...
 if [ ! -f ${LOCKFILE} ]; then
 echo "Unable to create lockfile ${LOCKFILE}!"
 exit 1
 fi
 echo "Created lockfile ${LOCKFILE}"
}

cleanup_lock(){
 echo "Cleaning up... "
 rm -f ${LOCKFILE}
 if [ -f ${LOCKFILE} ]; then
 echo "Unable to delete lockfile ${LOCKFILE}!"
 exit 1
 fi
 echo "Ok, lock file ${LOCKFILE} removed."
}