One instance at a time with PID file in Bash
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

The One instance at a time with PID file in Bash by Craig Andrews, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.
Categories: Uncategorized
PID_FILE=”/var/run/my_prog.pid”
## Check to see if the program is running
if [[ -e ${PID_FILE} ]]; then
## Capture the ‘pid’ number in ‘pid’ variable
pid=$( ${PID_FILE}
do something
## Remove the pid file if it exists
if [[ -e ${PID_FILE} ]]; then
rm -f ${PID_FILE}
fi
Your syntax is a bit wrong, when I ran the command the output of kill got redirected to the file 1.
Here is the syntax that worked for me:
if kill -0 $pid > /dev/null 2>&1; then
echo “Already running”
exit 1
else
rm $pidfile
fi
fi
echo $$ > $pidfile
No copy/paste that way, and makes it more interesting