0

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?

August Karlstrom
  • 10,773
  • 7
  • 38
  • 60

3 Answers3

1

You can try

eval echo '$'key$i
Alex Sveshnikov
  • 4,214
  • 1
  • 10
  • 26
1

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
Gro
  • 1,613
  • 1
  • 13
  • 19
0

There is an answer to this question here: https://stackoverflow.com/a/917313/10693596

Short answer is this is not possible in bash.

Update: depending on what you are ultimately after, using indirect expansion might work: https://stackoverflow.com/a/42066820/10693596

SultanOrazbayev
  • 14,900
  • 3
  • 16
  • 46