0

We would like to echo the value of a shell variable which has another variable string in its variable name. eg:

we want the following output

var1=1
var2=2

We tried several various forms similar to the one below but they don't work

for j in {1..2}
do
   export var${j}=$j
   echo "var${j}=${var${j}}"
done 

How do we set and echo shell variables containing variable string in their name?

Thank you

3

In bash (or ksh), you can use the indirection syntax ${!var} to reference the variable whose name is the value of $var. It has to be the complete name, so you have to do it like this:

for j in {1..2}; do
   # This could have been declare instead of export if you don't need
   # to export the variable.
   export var${j}=$j
   varname=var$j
   echo "var${j}=${!varname}"
done
0

You can do this as @rici explained but it is rarely a good idea. You could achieve the same thing with a simpler syntax if you use arrays instead:

var=("1" "2");
for j in {0..1}
do
    echo "var$j : ${var[$j]}"
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.