Bash: Variable variables

Nod

Honorary Master
Joined
Jul 22, 2005
Messages
10,968
Reaction score
2,715
Location
Darling
Sometimes it is needed to make use of variable variables.
Lets say you want to build up a variable name by using another variable.
The first part of the variable is always the same (CMD in this case), but you have an incremental number behind it.

If we have:
Code:
# CMD1=one
# CMD2=two
# CMD3=three
# CMD4=four

You could print it by using:
Code:
for i in $CMD1 $CMD2 $CMD3 $CMD4
do
     echo $i
done
This would work if you only have a small number of variables.

If you have a few hundred, then this would work better:
Code:
# for i in `seq 1 4`
> do 
>      var="CMD${i}"
>      echo ${!var}
> done
one
two
three
four
 
Top
Sign up to the MyBroadband newsletter
X