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?

Stephen
  • 6,027
  • 4
  • 37
  • 55

7 Answers7

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
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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.

Dummy00001
  • 16,630
  • 5
  • 41
  • 63
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
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
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
Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
  • 1
    Part of my answer was previously posted by @Dummy00001 -- the only person who had actually answered the question as asked. – Brent Bradburn Apr 02 '14 at 16:16
3
for I in {1..5}; do
    echo $((VAR$I))
done
Mokhtar
  • 109
  • 2
  • 7
1

Yes. See Advanced Bash-Scripting Guide

gerardw
  • 5,822
  • 46
  • 39
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

Anthony
  • 9,451
  • 9
  • 45
  • 72