tags:

views:

30

answers:

4

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?

+2  A: 

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
Ignacio Vazquez-Abrams
+1 for but don't do that. Use an array instead.
Nifle
Thanks for the advice re arrays. Using your and pax's post, I managed to get it working. Cheers guys.
Stephen
+1  A: 

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
paxdiablo
A: 

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

Shynthriir
+1  A: 
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.

Dummy00001