0

i am trying to increment a variable name inside a for loop to get 4 dynamic variable in each loop, this is an example

while read line
do
        for n in `seq 1 4`
                do
                vr$n=$(echo -e "$line" | awk '{print $'$n'}')
                #test
                echo vr$n
        done
done < rst.txt

cat rst.txt 
AAA BBB CCC DDD
111 222 333 444
*** --- /// +++

my problem is that when i try to execute the script it try to execute the result in the variable and i get an error 'command not found' any idea plz? thanks

0

1 Answer 1

0

Naming a variable with a variable (vr$n=value) is not possible without an export. However, I suggest to use an array instead:

vr[$n]=$(echo -e "$line" | awk '{print $'$n'}')

and reference the value afterwards with a syntax like this:

echo ${vr[$n]}
2
  • it worked thanks, just a small question, i think name of this vars will be vr[n] (vr[1], vr[2], vr[3] ...), if i plan to use this vars after on the same script file so no need to export it i need just to call the var with his name exp : echo vr[1] and to run the script need i to source it (source ./my_script.sh) thanks again for your help Apr 1, 2015 at 13:47
  • as i returned after more then 5 min i cannot edit my comment. tested and working as expected, no need to source the script. Apr 1, 2015 at 13:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .