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?

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

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 }"

Ok, this works:

#! /bin/sh -x

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

Good call,

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

, Mike

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.