Is it possible to build variable names from other variables in bash? [duplicate]

I apologise for the pretty terrible title - and the poor quality post - but what I basically want to do is this:

for I in 1 2 3 4
    echo $VAR$I # echo the contents of $VAR1, $VAR2, $VAR3, etc.

Obviously the above does not work - it will (I think) try and echo the variable called $VAR$I Is this possible in Bash?


Yes, but don't do that. Use an array instead.

If you still insist on doing it that way...

$ foo1=123
$ bar=foo1
$ echo "${!bar}"
123

for I in 1 2 3 4 5; do
    TMP="VAR$I"
    echo ${!TMP}
done

I have a general rule that if I need indirect access to variables (ditto arrays), then it is time to convert the script from shell into Perl/Python/etc. Advanced coding in shell though possible quickly becomes a mess.