30

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?

0

7 Answers 7

36

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
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for but don't do that. Use an array instead.
Thanks for the advice re arrays. Using your and pax's post, I managed to get it working. Cheers guys.
it doesnt work for kshell
10
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.

Comments

5

You should think about using bash arrays for this sort of work:

pax> set arr=(9 8 7 6)
pax> set idx=2
pax> echo ${arr[!idx]}
7

Comments

4

For the case where you don't want to refactor your variables into arrays...

One way...

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

Another way...

$ for I in 1 2 3 4; do eval echo \$$(eval echo VAR$I) ; done

I haven't found a simpler way that works. For example, this does not work...

$ for I in 1 2 3 4; do echo ${!VAR$I} ; done
bash: ${!VAR$I}: bad substitution

1 Comment

Part of my answer was previously posted by @Dummy00001 -- the only person who had actually answered the question as asked.
3
for I in {1..5}; do
    echo $((VAR$I))
done

Comments

1

Yes. See Advanced Bash-Scripting Guide

1 Comment

It would have been nice to transcribe some part of the linked page for direct understanding in your answer... but such a great reference!
0

This definately looks like an array type of situation. Here's a link that has a very nice discussion (with many examples) of how to use arrays in bash: Arrays

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.