是否可以从 bash 中的其他变量构建变量名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3963494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to build variable names from other variables in bash?
提问by Stephen
I apologise for the pretty terrible title - and the poor quality post - but what I basically want to do is this:
我为非常糟糕的标题 - 以及质量差的帖子 - 但我基本上想做的是:
for I in 1 2 3 4
echo $VAR$I # echo the contents of $VAR1, $VAR2, $VAR3, etc.
Obviously the above does not work - it will (I think) try and echo the variable called $VAR$I
Is this possible in Bash?
显然,上面的方法不起作用 - 它会(我认为)尝试并回显名为$VAR$I
Is this possible in Bash的变量?
回答by Ignacio Vazquez-Abrams
Yes, but don't do that. Use an array instead.
是的,但不要那样做。改用数组。
If you still insist on doing it that way...
如果你还坚持这样做......
$ foo1=123
$ bar=foo1
$ echo "${!bar}"
123
回答by Dummy00001
for I in 1 2 3 4 5; do
TMP="VAR$I"
echo ${!TMP}
done
I have a general rule that if I need indirect access to variables (ditto arrays), then it is time to convert the script from shell into Perl/Python/etc. Advanced coding in shell though possible quickly becomes a mess.
我有一个一般规则,如果我需要间接访问变量(同上数组),那么是时候将脚本从 shell 转换为 Perl/Python/etc。在 shell 中进行高级编码尽管可能很快就会变得一团糟。
回答by nobar
For the case where you don't want to refactor your variables into arrays...
对于您不想将变量重构为数组的情况...
One way...
单程...
$ for I in 1 2 3 4; do TEMP=VAR$I ; echo ${!TEMP} ; done
Another way...
其它的办法...
$ for I in 1 2 3 4; do eval echo $$(eval echo VAR$I) ; done
I haven't found a simpler way that works. For example, this does not work...
我还没有找到更简单的方法。例如,这不起作用......
$ for I in 1 2 3 4; do echo ${!VAR$I} ; done
bash: ${!VAR$I}: bad substitution
回答by paxdiablo
You should think about using bash
arrays for this sort of work:
您应该考虑将bash
数组用于此类工作:
pax> set arr=(9 8 7 6)
pax> set idx=2
pax> echo ${arr[!idx]}
7
回答by Ahmed Mokhtar
for I in {1..5}; do
echo $((VAR$I))
done
回答by gerardw
Yes. See Advanced Bash-Scripting Guide
是的。请参阅高级 Bash 脚本指南