0

I doing a proof of concept script to automate getting a field from ps.

Currently, the script takes 2 imputs and I'm almost there but cannot get awk to recognize $2.

I want to invoke it like this: #./script init 2 (search for init and get PID). Obviously, $2 to awk will return PID but I'm trying to grab whichever field I want.

#! /bin/sh -x

ps -ef | grep $1 | grep -v grep | awk '{ print "$"$2"" }'

Any thoughts?

2
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by eggi
0

Hey There,

You just need to double quote your awk statement so it processes $2 from the command line instead of internally - like this

awk "{print \$2}"

and you should be good :)

Only question is do you want the second column from init's ps output?

If so, you should just do a regular awk '{print $2}' since that will print out the second column of all the lines matched by your grep

Hope that helps,

Mike

0

Mike: after double quoting, it's still interpreting it as $2:

[root@bleargh scripts]# ./dollarsign2.sh httpd 99
+ ps -ef
+ grep httpd
+ awk '{ print $2 }'
3053
3055
3188
7718
7719
7720
7721
7722
7723
7724
7725

#! /bin/sh -x

ps -ef | grep $1 | awk "{ print \$2 }"
0

Ok, this works:

#! /bin/sh -x

ps -ef | grep $1 | awk -v var=$2 '{ print $var}'
0

Good call,

I obviously misunderstood, given my reply - when I re-read your question. Apologies :P

, Mike

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.