Bash中变量变量的变化(Variation on a Variable Variable in Bash)

编程入门 行业动态 更新时间:2024-10-28 13:22:56
Bash中变量变量的变化(Variation on a Variable Variable in Bash)

我正在寻找一种方法来将字符串添加到bash中的变量名称并将其作为新变量进行评估。 例:

#!/bin/bash file="filename" declare ${file}_info="about a file" declare ${file}_status="status of file" declare ${file}_number="29083451" echo ${${file}_info} # <-- This fails with error: "bad substitution"

有没有办法做到这一点?

我实际上并没有在任何地方的任何生产代码中实现它 。 我只想知道是否有某种方法可以使用变量和字符串创建变量名称。 这似乎是一个有趣的问题。

另请注意,我不是在询问bash间接,这是使用${!x}来将变量的内容作为变量进行评估。

I am looking for a way to add a string to a variable name in bash and evaluate this as a new variable. Example:

#!/bin/bash file="filename" declare ${file}_info="about a file" declare ${file}_status="status of file" declare ${file}_number="29083451" echo ${${file}_info} # <-- This fails with error: "bad substitution"

Is there a way to do this?

I'm not actually implementing this in any production code anywhere. I just want to know if there is some way to create a variable name using a variable and a string. It seemed like an interesting problem.

Also note that I am not asking about bash indirection, which is the use of ${!x} to evaluate the contents of a variable as a variable.

最满意答案

你不是在询问间接问题,但这可以帮助你:

info=$file\_info echo ${!info}

You aren't asking about indirection, but that's what can help you:

info=$file\_info echo ${!info}

更多推荐

本文发布于:2023-07-22 10:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219243.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Bash   Variable   Variation

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!