是否可以从 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:46:33  来源:igfitidea点击:

Is it possible to build variable names from other variables in bash?

bashvariables

提问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$IIs this possible in Bash?

显然,上面的方法不起作用 - 它会(我认为)尝试并回显名为$VAR$IIs 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 basharrays 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

回答by Anthony

This definately looks like an array type of situation. Here's a link that has a very nice discussion (with many examples) of how to use arrays in bash: Arrays

这绝对看起来像一种数组类型的情况。这是一个关于如何在 bash 中使用数组的非常好的讨论(有很多例子)的链接:Arrays