script grepping for itself returns additional value
I have a script that I do not run if it is already running. So I put in a check to make sure it is not running already by grepping the processes to make sure someone else is not running the script already. The problem is, within the script it reports as 2 processes are running instead of just the 1 even though I have another terminal open while it is running to show that there is really only one process.
This was fine because I simply said if the process count is higher than 2, then close out. However, now we use this script across several machines and when I do my check, since it is looking for the process on a different machine, if it is running over there, it returns 1 as I would expect. This means I have to redo my logic in my script to account for 2 processes on the system I am currently running the script on and 1 process for any other system.
I am trying to figure out why it does this. I am assuming it has something to do with a script creating its own instance of the shell, but I am not entirely sure what is going on so I was hoping someone could educate me. :)
This is the basics of the part of the script I am referring to:
Code:
me=`hostname`
for I in ${array[@]}
do
* * if ["$I" == "$me" ] ; then
* * * * isRunning=`ps -elf | grep script.sh | grep -v grep | grep -v vi | wc -l`
* * else
* * * * isRunning=`ssh -x user@"$I" 'ps -elf | grep script.sh | grep -v grep | grep -v vi | wc -l'`
* * fi
* * if [ $isRunning -gt 2 \ ; then
* * * * echo script.sh is already running on $I... Cannot run more than one instance of this script at a time."
* * * * exit
* * fi
done
so basically, I just realized today that it doesn't do the same 2 count when I ssh to another machine with it running since it is on another machine so I have to duplicate that "if isRunning" statement and put it within the first if/else statements so I can do one for the local machine with 2 and one for a remote machine with 1.
I am willing to take criticisms and advice on my code as well. I am always looking for ways to improve.
thanks,
Jeremy