Search code examples
bashshposixdynamic-variables

Create variables with dynamic index in bash


My code should work with #!/bin/sh
Is there a method how to declare a variables in loop with iteration number?
CODE:

n=0
somestring="asdf asdf"
while [ $n -le 10 ]
do
    "var$n"="$somestring"
done

# now it is possible to call variables var0, var1, var2,...
>> echo $var2
asdf asdf   

Thank you for answer!


Solution

  • You can use export :

    while [ $n -le 10 ]
    do
        export "var$n=$somestring"
        n=$((n+1))
    done
    

    Or eval :

    while [ $n -le 10 ]
    do
        eval "var$n=\"$somestring\""
        n=$((n+1))
    done