0

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 ?

asked Jul 2, 2012 at 6:45
2
  • What would you do with its PID if you found it? By the time it is available, the command has completed, so the PID is no longer valid. Commented Jul 2, 2012 at 6:48
  • Suppose i obtain it in the loop to compare with some value ? Commented Jul 2, 2012 at 6:49

2 Answers 2

1

I'm going out on a limb here, and understand this looks more like a comment.

Why do you need the PID of the grep command?

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 myproj but also an item about your grep command? If so, try the following:

 for i in `ps -ax | grep -v grep | grep "myproj"`
 do
 echo $i
 done

The -v switch basically inverts the pattern, so grep -v grep (or grep -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 mygrepling

However, in your particular case, where you only look for "myproj" it will do.

Or you could simply use

 for i in `ps -ax | grep "my[p]roj"`
 do
 echo $i
 done

That way there is no need to know the PID of the grep command, because it simply never shows up as a loop iteration.

answered Jul 2, 2012 at 6:54
Sign up to request clarification or add additional context in comments.

1 Comment

OK..what does the -v switch with grep do ?
1

When you run a process in background, you can get its PID in $!

 $ ps aux | grep dddddd & echo $!
 [1] 27948
 27948
 ic 27948 0.0 0.0 3932 760 pts/3 R 08:49 0:00 grep dddddd

When in foreground --- the process does not exist anymore at the point you want to find its PID. When you are in the loop, the for statement is already executed and grep is already exited, so you can not find its PID anymore.

answered Jul 2, 2012 at 6:51

2 Comments

Thanks!! Ill have to run it in background to get its PID. :)
Of course you can do it, but may be there are other ways to solve your task. Run grep in background and find its PID, well... it is a little bit strange :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.