VAR1=ABC;
VAR2=XYZ;
VAR3=PQR;
I want to print value of VAR1,VAR2 and VAR3 in a for loop. Please help!
In a for loop i am trying to do echo $VAR$i
Expected O/P:
ABC
XYZ
PQR
Actual Output:
1
2
3
Use an array:
VAR[1]=ABC
VAR[2]=XYZ
VAR[3]=PQR
for i in 1 2 3 ; do
echo ${VAR[i]}
done
Or, use the variable indirection:
VAR1=ABC
VAR2=XYZ
VAR3=PQR
for i in 1 2 3 ; do
name=VAR$i
echo ${!name}
done
You can do it like this:
for i in 1 2 3
do
eval "echo \$VAR${i}"
done
The key point is the eval command.
$ VAR1=ABC; VAR2=XYZ; VAR3=PQR;
$ for i in 1 2 3; do eval "echo \$VAR${i}"; done
ABC
XYZ
PQR
sh, bash provides alternatives (see choroba's answer) that don't require you to use the possibly dangerous eval command.Instead of
echo $VAR$iin for loop do
varx=$varx$var$i
and initialize varx as empty string and at end do
echo $varx
This is for printing without space as the question suggests.