Pages

Thursday, March 27, 2008

Accessing the Command Line Args of a Shell Script from an Embedded AWK script

Let's start with the example of the skeleton of a shell script running on Sun Solaris.
#!/bin/sh

if [ $# -lt 2 ]; then
echo "Usage: pmap_mf.sh "
exit
fi
...
pmap -x $PIDS | grep total | awk 'BEGIN { FS = " " } {print $1,$2,$3,$4,$5} {rss+=$4}
{private+=$5} END {print "Total Private mem: "private/1024" M Total RSS mem: "rss/1024" M Total
Shared mem: " (rss-private)/1024 "M **** For 10000 user load: per user memory footprint is:
"((private/1024)+(((rss-private)/1024)/NR))/10000" MB/user"}'

Notice the highlighted hard coded number for the number of users. The goal is to read the number of users value from the command line rather than editing the script every time there is a change in the number of users.

Assuming there is a shell script with an embedded AWK script like the one shown in the above example, how the awk script can access the command line arguments supplied to the top level shell script?

It is not possible to use $1, $2 etc., because $1 and $2 will hold the string tokens returned by the awk output. For example, if awk returned "total Kb 472648 242936 57768", then $1 will hold the string "total" and $2 will have "Kb".

The solution/trick is to pass the required command line arguments from the main shell script to the awk script with the -v option of awk; and then to access the arguments supplied for the awk script either by directly referencing the argument name or by using ARGC & the ARGV array notation (just like C/C++).

Note:
/usr/bin/awk on Sun Solaris doesn't accept the -v option. Use /usr/bin/nawk or /usr/xpg4/bin/awk on Solaris.

Now with all the above information, the last line of code can be modified as shown below to get rid of the hard coded numbers:
pmap -x $PIDS | grep total | nawk -v Arg1=$2 'BEGIN { FS = " " } {print $1,$2,$3,$4,$5} {rss+=$4} {private+=$5} 
END {print "Total Private mem: "private/1024" M Total RSS mem: "rss/1024" M Total Shared mem: "
(rss-private)/1024 "M **** For ", Arg1, " user load: per user memory footprint is:
"((private/1024)+(((rss-private)/1024)/NR))/Arg1" MB/user"}'

_______________
Technorati Tags:
| | | |

No comments:

Post a Comment