Lockfiles in Bash

Here’s a simple ‘skeleton’ script that will allow your Bash scripts to use a PID file, or ‘lockfile’. This ensures that only one instance can run at a time which is useful for daily Cron activities such as mirror updates.

#!/bin/bash
pidfile=/var/run/sync.pid
if [ -e $pidfile ]; then
pid=`cat $pidfile`
if kill -0 &>1 > /dev/null $pid; then
echo "Already running"
exit 1
else
rm $pidfile
fi
fi
echo $$ > $pidfile
#do your thing here
rm $pidfile

Categories: Linux. Bookmark the permalink. Comments Off on Lockfiles in Bash

Comments are closed.