Using grep to extract PID

Hi unix experts!

I need help to solve the following problem:

I'm getting the prstat info:
stats=`prstat 0 1` #dont worry about how many processes are running I'm aware that no all processes will be listed without the -n (specify number)

then I'm doing the following to extract the PIDs:
pids=`echo "$stats" | awk '{print $1}'`
pids=`echo $pids | sed -e 's/PID//' | sed -e 's/Total://'` #to remove the Total and PID lines which are not required

Then I'm iterating through the PID's and trying to grep for each of the PID's my running ps. That way I'm able to look up things like the arguments and command rather than just the PID. The aim of doing this is eventually I want to replace the PID output from prstat to something more meaningful with command and args info for that process. This is the code for that:

for i in $pids
do
output=`ps -eaf -o pid,comm,args | grep ^' '*$i' '`
...
The output I'm getting is :
Usage: grep -hblcnsviw pattern file . . .
prstat_script.sh: *7 : not found

If I put in the escape characters i.e. output=`ps -eaf -o pid,comm,args | grep \^\' \'*$i\' \'` then I get:
grep: can't open '*7'
grep: can't open '

This is obviously because grep sees a space and tries to use '$i' as the file name. This is not what I want to achieve though.

If I run the non-escaped version on the command line (not in a bash script) then it works fine and gives me the output i desire, e.g.:

bash-3.00$ ps -eaf -o pid,comm,args | grep ^' '*1008' '

gives the output:

1008 /usr/lib/saf/ttymon /usr/lib/saf/ttymon

Thing is I don't know how to do this in the bash script.

Your help would really be appreciated.

Thanks very much in advance.

Sanjay

Hmm... works for me -

$ 
$ cat -n f0.sh
     1  #!/bin/bash
     2  pids="2060 2061 2062"
     3  for i in $pids
     4  do
     5    output=`ps eaf -o pid,comm,args | grep ^' '*$i' '`
     6    echo $output
     7  done
$ 
$ ./f0.sh
2060 mingetty /sbin/mingetty tty2
2061 mingetty /sbin/mingetty tty3
2062 mingetty /sbin/mingetty tty6
$ 

Try awk perhaps ?

$ 
$ ps eaf -o pid,comm,args | awk '/^ 2060/'
 2060 mingetty        /sbin/mingetty tty2
$ 
$ ps eaf -o pid,comm,args | awk '/^ *2060/'
 2060 mingetty        /sbin/mingetty tty2
$ 
$ cat -n f1.sh
     1  #!/bin/bash
     2  pids="2060 2061 2062"
     3  for i in $pids
     4  do
     5    output=`ps eaf -o pid,comm,args | awk "/^ *$i/"`
     6    echo $output
     7  done
$ 
$ ./f1.sh
2060 mingetty /sbin/mingetty tty2
2061 mingetty /sbin/mingetty tty3
2062 mingetty /sbin/mingetty tty6
$ 
$ 

tyler_durden

I did get it working in the end as a result of your post durden_tyler. It has to do with the way that you were running the script. I was using sh to run the script rather than executing it using ./

Once I figured that one out I was able to get it to work.

Thanks.