引用附加变量? [英] Reference an appended variable?
本文介绍了引用附加变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在bash脚本中执行此操作?
How can I do this in a bash script?
#!/bin/sh
func() {
export ${NAME}_SUFFIX=`result_of_some_command`
}
NAME=my_name
func
# This variable will become my_name_SUFFIX
# but how can I reference it using $NAME?
echo ${${NAME}_SUFFIX} # Doesn't work...
如果可以通过函数调用使用,我会使用 declare ,但似乎没有.另外,我的声明版本不支持-x.
I'd use declare if it would work through function calls, but it seems it doesn't. Also, my version of declare doesn't support -x.
推荐答案
我知道您要做什么... 警告 ...评估"是一种糟糕的方法而变量间接寻址则更好.但是,这就是您要的.
I know what you're trying to do...warning..."eval" is a terrible way to do it and variable indirection is better. But, here is what you asked for.
对脚本进行一个简单的更改:
One simple change to your script:
将导出"更改为评估"即可使用.您一直都在那里!哦,如下所示更改您的"echo"语句.
Change "export" to "eval" and it'll work. You were most of the way there! Oh, and change your "echo" statement as shown below.
示例:
#!/bin/sh
func() {
eval ${NAME}_SUFFIX=`result_of_some_command`
}
NAME=my_name
func
# This variable will become my_name_SUFFIX
# but how can I reference it using $NAME?
eval echo "\${${NAME}_SUFFIX}"
这篇关于引用附加变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文