How to check in a bash script if something is running and exit if it is


Question

I have a script that runs every 15 minutes but sometimes if the box is busy it hangs and the next process will start before the first one is finished creating a snowball effect. How can I add a couple lines to the bash script to check to see if something is running first before starting?

1
10
5/29/2009 5:04:36 PM

Accepted Answer

In lieu of pidfiles, as long as your script has a uniquely identifiable name you can do something like this:

#!/bin/bash
COMMAND=$0
# exit if I am already running
RUNNING=`ps --no-headers -C${COMMAND} | wc -l`
if [ ${RUNNING} -gt 1 ]; then
  echo "Previous ${COMMAND} is still running."
  exit 1
fi
... rest of script ...
3
5/29/2009 8:22:12 PM

You can use pidof -x if you know the process name, or kill -0 if you know the PID.

Example:

if pidof -x vim > /dev/null
then
    echo "Vim already running"
    exit 1
fi

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon