Dynamic variable assignment

Hi All,

I have the below scenario:

A file test.cfg with three fields>>

DATA1 DATA2 DATA3

In the script I need to assign each of the fields to variables. The number of fields will not be constant (this case we have three). Im trying to do something like this:

NUM=1
OUT_DAT_NO=3

while [ $NUM -le $OUT_DAT_NO ]
do
OUT_DAT$NUM=`cat test.cfg | awk '{print $NUM}'`
NUM=`expr $NUM + 1`
done

The output should be like this:

OUT_DAT1=DATA1
OUT_DAT2=DATA2
OUT_DAT3=DATA3

Is there any way of doing this in bash?

Thanks,
D

You can use read. bash assigns values to variables for the fields present, leaves the rest as zero-length strings.

cat test.cfg | read OUT_DAT1 OUT_DAT2 OUT_DAT3 OUT_DAT4

I there are three fields this [ -z $OUT_DAT4 ] will be true because OUT_DAT4 is zero-length

Consider:

set `head -1 test.cfg`
for element;do
        echo $element
done

You can use $(head -1 test.cfg) if you want something more bash/ksh specific.

Note... my soln only works up to the limit of parameters that could be put on the shell command line.

So number of fields and size of the data in the field will cause it to blow up possibly.

Try this:

awk '{for(i=1;i<=NF;i++) printf("%s%s\n","OUT_"$i"=",$i)}' filename

cheers,
Devaraj Takhellambam