In a shell script lets say i have run a command like this
for i in `ps -ax|grep "myproj"`
do
echo $i
done
Here, the grep command would be executed as a separate process. Then how do i get its PID in the shell script ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’m going out on a limb here, and understand this looks more like a comment.
Why do you need the PID of the
grepcommand?In your comment you say you want to compare it in the loop against something. I would suppose that it is your issue that that the loop will (sometimes) not only include
myprojbut also an item about your grep command? If so, try the following:The
-vswitch basically inverts the pattern, sogrep -v grep(orgrep -v "grep", which maybe looks a bit less awkward) will include only lines that do not include the string “grep” (see man grep).Note that this maybe overly vague for some cases, for example if the pattern you actually look for also contains the string “grep”. For example, the following might not work as you’d expect:
ps -ax | grep -v grep | grep mygreplingHowever, in your particular case, where you only look for “myproj” it will do.
Or you could simply use
That way there is no need to know the PID of the grep command, because it simply never shows up as a loop iteration.