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?

user7328234
  • 393
  • 7
  • 23

1 Answers1

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
mklement0
  • 382,024
  • 64
  • 607
  • 775
merlin2011
  • 71,677
  • 44
  • 195
  • 329