Simple bash locking
I often need to create lock files in my scripts, so crontab doesn’t spawn more than one process. This is a simple bash lock file function I like to use:
function create_lock {
LOCK_NAME=$1
if [[ -e "$LOCK_NAME" ]]
then
OLDPID=`cat $LOCK_NAME`
if ps p $OLDPID > /dev/null
then
return 1
fi
rm $LOCK_NAME
fi
echo $$ > $LOCK_NAME
return 0
}
create_lock doesn’t handle race conditions, but it is typically good enough for me.
cp 9:57 am on January 14, 2010 Permalink |
You can avoid the race condition by using “set -o noclobber”. Like this:
if ! (set -o noclobber; echo “$$” > “/tmp/lock”) 2> /dev/null; then
echo “locking failed”
exit 1
fi