[Solved] Looking for script running before I run script again

Good afternoon!

I have a script in cron that runs every ten minutes. Normally it only takes a minute or so to complete. However there are times when the amount of data it is looking at is large, and it has taken 20 minutes.

So I want for it to look for the script before it starts.

I was going to put something like this in the beginning"

ps -ef | grep "stats.sh" | grep -v "grep"

And if it found a process, then it will just exit. Otherwise, it will continue on like normal. My thought process is that this runs every ten minutes and if there is something going on that is causing it take longer than 10 minutes (or really 7 or 8) then they won't all stack up running at the same time.

It is on the tip of my brain, but I can't seem to find it.

I was thinking of doing this,

ps -ef | grep "stats.sh" | grep -v "grep" > /var/tmp/stats.tmp
namedtmp=/var/tmp/stats.tmp
if [ -s $namedtmp ]
then
exit
else
then continue on with script
fi

What do you think? Any suggestions?

This is causing a problem, because at one time it took up all of the CPU and memory and nobody could log in via SSH even.

pidfile=/var/tmp/stats.pid

# exit if another is running
[ -e "$pidfile" ] && exit

# create pid file
echo $$ >"$pidfile"

# delete pid file on exit (may have to do this definitely depending on shell)
trap "rm $pidfile" EXIT
2 Likes

or if you have 'fuser' - there're many ways to skin that proverbial 'cat':

#!/bin/ksh

myPID="$$"
echo "My pid->[${myPID}]"
FUSERout=$(${FUSER} $0 2>/dev/null)
echo "fuser ->[${FUSERout}]"
numProc=$(echo "${FUSERout}" | nawk '{print NF}')
if [ "${numProc}" -gt 1 ]; then
   echo "[$0]: is ALREADY running - bailing..."
   exit
fi

....
here goes the rest of your script

I use something very my like neutronscott's solution myself.

It can be worth adding a check for "stale" pidfiles left around after a reboot, or kill of the process. Something like this:

if [ -e "$pidfile" ]
then
    [ -d /proc/$(cat "$pidfile") ] && exit
    echo "Removing stale pidfile: $pidfile"
    rm -f "$pidfile"
fi

That's also a good idea, but a more portable (read: non-linux) approach would be with kill -0 $(cat "$pidfile") && exit .

Thanks Scott! That is working like I had hoped.

try this at begning of the script

p_count=`ps -ef | grep process.sh | grep -v "grep" | wc -l`
if test $p_count -le 1
then

your script

else
echo "Script is Already Running with Another User,Please try after some time"

it will work

Yes, it will work but is not optimal. The better approach is the use of a pidfile as others have suggested.

Save a process be not using grep -v grep. do it like this instead:

p_count=`ps -ef | grep [p]rocess.sh | wc -l`

This matches the text "process.sh" but not itself (the string "[p]rocess.sh").