Skip to content

Instantly share code, notes, and snippets.

@channprj
Last active November 2, 2016 02:49
Show Gist options
  • Save channprj/68adf66fc26e0535ea11542f10aa5343 to your computer and use it in GitHub Desktop.
Save channprj/68adf66fc26e0535ea11542f10aa5343 to your computer and use it in GitHub Desktop.
Preventing duplicate shell script executions
#!/bin/sh
# WIP prevent duplicate cron job shell executions.
# refer: http://bencane.com/2015/09/22/preventing-duplicate-cron-job-executions/
do_function() {
# do something...
}
PIDFILE=/path/to/<YOUR_PID_FILE>.pid
if [ -f $PIDFILE ] ## if pid file exist and it is not a directory
then
## if there really is another instance of this script running
PID=$(cat $PIDFILE)
ps -p $PID > /dev/null 2>&1
if [ $? -eq 0 ] ## if exit code is equal to 0 with ps command
then
echo "Process already running"
exit 1
else
## process not found assume not running
echo $$ > $PIDFILE
if [ $? -ne 0 ] # if exit code is not equal to 0 with echo command
then
echo "Could not create PID file"
exit 1
fi
fi
else ## if pid file doesn't exist
echo $$ > $PIDFILE
if [ $? -ne 0 ] ## if exit code is not equal to 0 with echo command
then
echo "Could not create PID file"
exit 1
fi
fi
do_function
rm $PIDFILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment