0
#!/bin/bash

list="one two three"
one=1
two=2 
three=3
for k in $list
do 
    echo $k
done

For the code above, output is:
one
two
three

But I always think it should output:
1
2
3
It's confusing. How to understand this?

0

1 Answer 1

2

The expansion $k just gives you the name of the variable as a string. If you want the value of the variable, you must use the parameter expansion syntax ${!k}. This is documented here.

#!/bin/bash

list="one two three"
one=1
two=2 
three=3
for k in $list
do 
        echo "${!k}"
done

Output

1
2
3
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.