Skip to content

Simple shell lock implementation on Linux

Sometimes you want to avoid running second instance of some shell script. Locking implementation is not very hard:

LOCK_FILE=$0.lock
test -f $LOCK_FILE && {
        PID=`cat $LOCK_FILE`
        echo "$LOCK_FILE exists, PID=$PID, exiting"
        exit 1
}
echo $$ > $LOCK_FILE
trap "rm $LOCK_FILE" 0 2 3 15