简体   繁体   中英

BASH: Cannot awk with a variable in a while loop

I have a Problem when trying to awk a READ input in a while loop.

This is my code:

#!/bin/bash

read -p "Please enter the Array LUN ID (ALU) you wish to query, separated by a comma (e.g. 2036,2037,2045): " ARRAY_LUNS
LUN_NUMBER=`echo $ARRAY_LUNS | awk -F "," '{ for (i=1; i<NF; i++) printf $i"\n" ; print $NF }' | wc -w`
echo "you entered $LUN_NUMBER LUN's"

s=0
while [ $s -lt $LUN_NUMBER ];
do
        s=$[$s+1]
        LUN_ID=`echo $ARRAY_LUNS | awk -F, '{print $'$s'}' | awk -v n1="$s" 'NR==n1'`
        echo "NR $s :"
        echo "awk -v n1="$s" 'NR==n1'$LUN_ID"
done

No matter what options with awk i try, i dont get it to display more than the first entry before the comma. It looks to me, like the loop has some problems to get the variable s counted upwards. But on the other hand, the code line:

LUN_ID=`echo $ARRAY_LUNS | awk -F, '{print $'$s'}' | awk -v n1="$s" 'NR==n1'`

works just great! Any idea on how to solve this. Another solution to my READ input would be just fine as well.

#!/bin/bash

typeset -a ARRAY_LUNS
IFS=, read -a -p "Please enter the Array LUN ID (ALU) you wish to query, separated by a comma (e.g. 2036,2037,2045): " ARRAY_LUNS
LUN_NUMBER="${#ARRAY_LUNS[@]}"
echo "you entered $LUN_NUMBER LUNs"

for((s=0;s<LUN_NUMBER;s++))
do
     echo "LUN id $s: ${ARRAY_LUNS[s]}"
done

Why does your awk code not work?

The problem is not the counter. I said The last awk command in the pipe ie

awk -v n1="$s" 'NR==n1' .

This awk code tries to print the first line when s is 1, the second line when s is 2, the third line when s is 3, and so on... But how many lines are printed by echo $ARRAY_LUNS ? Just ONE ... there is no second line, no third line... just ONE line and just ONE line is printed.

That line contains all LUN_IDs in ONE LINE , ie, one LUN_ID next to another LUN_ID, like this way:

34 45 21 223

NOT this way

34
45
21
223

Those LUN_IDs are fields printable by awk using $1 , $2 , $3 , ... and so on.
Therefore if you want you code to run fine just remove that last command in the pipe :

LUN_ID=$(echo "$ARRAY_LUNS" | awk -F, '{print $'$s'}')

Please, for any further question, firstly read this awk guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM