grep the number of self process

Dear All,

I plan to write a script and in the beginning, I will check if there's any existing previous process running, if YEs, then exit directly, if Not, then continue.

#!/bin/bash

NUM=`ps -ef | grep $0 | grep -v grep | wc -l`

ps -ef | grep $0 | grep -v grep
echo "NUM ==> $NUM"

if [ $NUM -ne 1 ]; then
   echo "previous processing running, exit"
   exit 1
fi

echo "Hello...  I got here.."

I can not understand, why running this script will return :

====================================
root 7815 29364 0 09:30 pts/0 00:00:00 /bin/bash ./2.sh
NUM ==> 2
previous processing running, exit

from "ps -ef | grep $0 | grep -v grep " command, it's obvious that only one line return, why $NUM will become 2 ??

any advice on this?

Thanks.

look into 'man fuser'.

you may want to take care of situations such as if someone is editing the same file in an editor, say using vi

check this
http://www.unix.com/shell-programming-scripting/35182-process.html\#post302106339

Well, I'm a little disappointed at the responses on this one... so... I'll try something a little different.

In your script, the return of 2 is happening for a very specific reason. I'll give you a clue first.

Instead of piping the ps command all the way through the word count, eliminate it and print out the return string from the ps command when you spawn it through the grave quotes.

I.e... STRING=`ps -aef | grep $0 | grep -v grep`

You will note that two lines are returned... look closely, the process ID's should give you a clue as to what the kernel is doing..

My return on a reduced example of your script is as follows:

aa@lnx2:~/bin$ 2.sh
aa        1530   537  0 18:29 pts/12   00:00:00 /bin/bash /home/aa/bin/2.sh
STRING ==> aa        1530   537  0 18:29 pts/12   00:00:00 /bin/bash /home/aa/bin/2.sh
aa        1534  1530  0 18:29 pts/12   00:00:00 /bin/bash /home/aa/bin/2.sh
NUM ==> 2

a tricky problem.... the answer is . . ..

the back-ticks are creating yet another sub-shell.

But even acknowledging that, these types of checks are tricky.
And I prefer to just check the existance of a lock file.

If it's there, quit.
Else, create it and continue processing.


FLOCK=/tmp/aardvark.lock

if [ -f $FLOCK ]; then
  echo already running since `cat $FLOCK`
  exit 1
fi

date > $FLOCK

echo continuing on my merry way...

This is the correct answer.