Tuesday, 26 June 2012

Bash script lock file

Here's the lock file mechanism that I use for some of my bash scripts.
I check if the lock file is older than a reasonable time for the script to execute completely just in case the script or the machine running it crashed in the middle of it's execution and the lock file hangs the process forever...
#!/bin/bash
#Check if the lockfile exists and is older than one day (1440 minutes)
minutes=1441
LOCKFILE=/tmp/extract.lock
if [ -f $LOCKFILE ]; then
    echo "Lockfile Exists"
    filestr=`find $LOCKFILE -mmin +$minutes -print`
    if [ "$filestr" = "" ]; then
        echo "Lockfile is not older than $minutes minutes, exiting!"
        exit 1
    else
        echo "Lockfile is older than $minutes minutes, ignoring it and proceeding normal execution!"
        rm $LOCKFILE
    fi
fi
touch $LOCKFILE
##Do your stuff here


rm $LOCKFILE
exit 0
Another approach is to store the PID of the current process in the lock file and check if the process is still running:
#!/bin/bash
LOCKFILE=/tmp/extract.lock
if [ -f $LOCKFILE ]; then
    echo "Lockfile Exists"
    #check if process is running
    MYPID=`head -n 1 "${LOCKFILE}"`
    TEST_RUNNING=`ps -p ${MYPID} | grep ${MYPID}`
    if [ -z "${TEST_RUNNING}" ]; then
        echo "The process is not running, resuming normal operation!"
        rm $LOCKFILE
    else
        echo "`basename $0` is already running [${MYPID}]"
        exit 1
    fi
fi
echo $$ > "${LOCKFILE}"
##Do your stuff here


rm $LOCKFILE
exit 0
The first approach will permit parallel execution of your scripts but will give the first instance an head start of 1 day (or whatever the time you define in the $minutes variable). Whilst the second method will only allow the start of another instance of the script when the previous has terminated.

Possibly Related Posts

1 comment:

  1. The "flock" utility manages file locks from within shell scripts or the command line.

    It's probably a bit easier then to do it all yourself.

    ReplyDelete