- The Musings of Chris Samuel - https://www.csamuel.org -

Exclusive locks in Bourne shell scripts

Been writing some stuff in shell that needs to be able to ensure it doesn’t start itself twice, so a bit of Googling for exclusive locks in shell scripts [1] brought me to this page on “advanced shell scripting” [2] which had something that looked good.

Problem is that when you put it into a script you’ll find it doesn’t actually work because of some trivial coding issues.

So here’s the fixed version of that function..

# Function to do atomic locking.
# Original found at http://members.toast.net/art.ross/rute/node24.html
# Fixed by Chris Samuel http://www.csamuel.org/

function my_lockfile ()
 {
         TEMPFILE="$1.$$"
         LOCKFILE="$1.lock"
         ( echo $$ > $TEMPFILE ) >& /dev/null || (
                 echo "You don't have permission to access `dirname $TEMPFILE`"
                 return 1
         )
         ln $TEMPFILE $LOCKFILE >& /dev/null && {
                 rm -f $TEMPFILE
                 return 0
         }
         kill -0 `cat $LOCKFILE` >& /dev/null && {
                 rm -f $TEMPFILE
                 return 1
         }
         echo "Removing stale lock file"
         rm -f $LOCKFILE
         ln $TEMPFILE $LOCKFILE >& /dev/null && {
                 rm -f $TEMPFILE
                 return 0
         }
         rm -f $TEMPFILE
         return 1
 }