Monthly Archives: August 2013

Using flock to ensure only one instance of a script can run

Whilst browsing, I came across the following post from Randall Schwartz of Perl and FLOSS Weekly fame.

“flock” is one of those utilities I’ve not used very much, but if you want to create a script and ensure that only a single instance of it can run at any one time then this is a really neat utility. No lock or PID files to mess with, no “ps -ef | grep” type of scripting to incorporate.


#!/bin/sh
(
if ! flock -n -x 200
then
echo "$$ cannot get flock"
exit 0
fi
echo "$$ start"
sleep 10 # real work would be here
echo "$$ end"
) 200< $0

One to file away for future use :)