英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论