Printing a specific line using AWK

Hi,

I have a script that fetches only specific information from fcinfo command. Below is a portion of the script.

#!/usr/bin/ksh
set -x
HBA_COUNT=`sudo fcinfo hba-port | grep -i state | awk 'END{print NR}'`
echo "$HBA_COUNT HBAs exist"
echo '........'

INDEX=1
while [wiki] $INDEX -le $HBA_COUNT [/wiki] ; do
HBA_STAT[$INDEX]=`sudo fcinfo hba-port | grep -i 'Port WWN' | awk 'NR==$INDEX' | awk '{print $NF}'`
print 'WWN:'
print ${HBA_STAT[$INDEX]}
(( INDEX=$INDEX+1 ))
done

The part in red is where I'm having trouble with. When I type
sudo fcinfo hba-port | grep -i 'Port WWN' | awk 'NR==1' | awk '{print $NF}'
into the command line, I have no problem displaying the WWN info (where the value in blue can vary).

Also, I noticed something funny where if i replace (in the script)
HBA_STAT[$INDEX]=`sudo fcinfo hba-port | grep -i 'Port WWN' | awk 'NR==$INDEX' | awk '{print $NF}'`
with
HBA_STAT[$INDEX]=`sudo fcinfo hba-port | grep -i 'state' | awk 'NR==$INDEX' | awk '{print $NF}'`
it still doesn't work, but once I change 'NR==$INDEX' with '$NR==INDEX', it works...
Can someone explain why this is happening and maybe correct me on the syntax if I'm doing something wrong?

Thanks

1 Like

The shell don't expand shell variables within single quotes, try this:

HBA_STAT[$INDEX]=`sudo fcinfo hba-port | grep -i 'Port WWN' | awk 'NR=='$INDEX | awk '{print $NF}'`

or with a awk variable:

HBA_STAT[$INDEX]=`sudo fcinfo hba-port | grep -i 'Port WWN' | awk -v var=$INDEX 'NR==var' | awk '{print $NF}'`

Thanks so much Franklin52 :D. The second method doesn't work but the first one does.