2
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

4 Answers 4

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the variable indirection. I wasn't aware it was possible to do it like that.
2

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.

Test

$ VAR1=ABC; VAR2=XYZ; VAR3=PQR;
$ for i in 1 2 3; do eval "echo \$VAR${i}"; done
ABC
XYZ
PQR

1 Comment

While this approach is necessary for vanilla sh, bash provides alternatives (see choroba's answer) that don't require you to use the possibly dangerous eval command.
0
echo "${VAR1}${VAR2}${VAR3}"

Simple as that. I don't think it make sense to create useless cycles just to concatenate several values into a string

Comments

-1

Instead of

echo $VAR$i
in 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.

1 Comment

This doesn't expand to the value of the three variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.