Often times, I only want a script to run one instance at a time. For example, if the the script is copying files, or rsync’ing between systems, it can be disastrous to have two instances running concurrently, and this situation is definitely possible if you run the script from cron.
I figured out a simple way to make sure only one instance runs at a time, and it has the added benefit that if the script dies midway through, another instance will start – a drawback of just using lock files without a pid.
Without further ado, here’s my script:
#!/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