如何执行 shell 变量的双重替换?

huangapple go评论48阅读模式
英文:

How do I perform double substitiution of shell variables?

问题

我有以下脚本存储在test.sh中:

#!/bin/sh

key1=foo
key2=bar
key3=baz

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

当我运行它时,我得到以下输出:

1
test.sh: 9: Bad substitution

我做错了什么?

英文:

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?

答案1

得分: 1

你可以尝试

eval echo '$'key$i
英文:

You can try

eval echo '$'key$i

答案2

得分: 1

这是你在寻找的吗?

#!/bin/sh

key1=foo
key2=bar
key3=baz

for i in 1 2 3; do
  echo $i
  eval echo $"key$i"
done

输出:

1
foo
2
bar
3
baz
英文:

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

答案3

得分: 0

这里有这个问题的答案:https://stackoverflow.com/a/917313/10693596

简短回答是在bash中不可能实现。

更新:根据你最终的需求,使用间接扩展可能会起作用:https://stackoverflow.com/a/42066820/10693596

英文:

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

huangapple
  • 本文由 发表于 2023年6月13日 18:54:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76464176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定