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.
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