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
  • 5,849
  • 4
  • 34
  • 53

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
  • 740,318
  • 145
  • 1,296
  • 1,325
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
  • 15,836
  • 5
  • 37
  • 58
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
  • 814,905
  • 225
  • 1,535
  • 1,899
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
  • 46,639
  • 15
  • 140
  • 156
  • 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
  • 99
  • 2
  • 7
1

Yes. See Advanced Bash-Scripting Guide

gerardw
  • 5,139
  • 41
  • 37
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,225
  • 9
  • 42
  • 71