Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell fragment to make sure only one instance a shell script runs at any given time [duplicate]

Tags:

shell

Possible Duplicate:
Quick-and-dirty way to ensure only one instance of a shell script is running at a time

At a previous workplace we used to have a highly-refined bash function called run-only-once that we could write into any long-running shell script, and then call it at the start of the script, which would check to see whether the script was already running as another process, and if so exit with a notification to STDOUT.

Does anyone have a function/fragment like this they could share?

Our old function (which I no longer have) would check for a PID file (in scriptname.$$ format) in /var/run, and use then either exit or simply continue. In the case where a PID file existed, it would do some checks to make sure that the process was still active. It also had a few options for controlling whether a notification was output at all.

From memory, our function only worked in bash. Bonus points for a /bin/sh version.

like image 587
Anon Gordon Avatar asked Dec 20 '25 02:12

Anon Gordon


1 Answers

Put this at the start of the script

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}

and at the end

if [ -f ${PIDFILE} ]; then
    rm ${PIDFILE}
fi

This first of all checks for the existence of the pid file and exits if it's present. If so then it confirms that a process under this script name with the old pid is running and exits if so. If not then it carries on and updates the script with the new pid file. The bit at the end checks for the existence of the pid file and deletes it, so the script can run next time.

Check permissions on /var/run are OK for your script though, otherwise create the PID file in another directory. Same directory as the script runs in would be fine.

like image 182
NeilInglis Avatar answered Dec 24 '25 04:12

NeilInglis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!