Search code examples
shposix

How do I perform double substitiution of shell variables?


I have the following script stored in test.sh:

#!/bin/sh

key1=foo
key2=bar
key3=baz

for i in 1 2 3; do
    echo $i
    echo ${key${i}}
done

When I run it I get the output

1
test.sh: 9: Bad substitution

What am I doing wrong?


Solution

  • Is this what you are looking for?

    #!/bin/sh
    
    key1=foo
    key2=bar
    key3=baz
    
    for i in 1 2 3; do
      echo $i
      eval echo \$"key$i"
    done
    

    Output:

    1
    foo
    2
    bar
    3
    baz