Skip to content

Instantly share code, notes, and snippets.

@scotu
Created August 25, 2014 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scotu/068cdd2e199d7bc902be to your computer and use it in GitHub Desktop.
Save scotu/068cdd2e199d7bc902be to your computer and use it in GitHub Desktop.
Wrapper to make sure a command is run only once at a time
#!/bin/sh
# taken from http://stackoverflow.com/a/959511/150932
SCRIPTNAME=`basename $0`
PIDFILE=/var/run/${SCRIPTNAME}.pid
if [ -f ${PIDFILE} ]; then
#verify if the process is actually still running under this pid
OLDPID=`cat ${PIDFILE}`
RESULT=`ps -ef | grep ${OLDPID} | grep ${SCRIPTNAME}`
if [ -n "${RESULT}" ]; then
echo "Script already running! Exiting"
exit 255
fi
fi
#grab pid of this process and update the pid file with it
PID=`ps -ef | grep ${SCRIPTNAME} | head -n1 | awk ' {print $2;} '`
echo ${PID} > ${PIDFILE}
echo "PUT YOUR COMMANDS IN PLACE OF THIS ECHO"
if [ -f ${PIDFILE} ]; then
rm ${PIDFILE}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment