【发布时间】:2012-08-31 21:55:15
【问题描述】:
我有一些代码可以自动创建某个名称的变量并为其分配一些值。代码如下:
myVariableName="zappo"
eval "${myVariableName}=zappo_value"
如何使用自动生成的变量名称访问该变量的值?所以,我正在寻找一些类似于以下的代码(但有效):
eval "echo ${${myVariableName}}"
(... 可用于 myVariableValue="$(eval "echo ${${myVariableName}}")"...)。
非常感谢您的帮助
如果您认为这种方法很疯狂并且想要提供更一般的建议,我正在研究的一般想法是在库中的函数中定义变量,其名称为 ${usage} 和 ${prerequisiteFunctions}。这些在函数中定义的变量将被一个询问函数访问,例如,该函数可以确保安装了先决条件等。所以这个询问函数中的循环是这样的:
for currentFunction in ${functionList}; do
echo "function: ${currentFunction}"
${currentFunction} -interrogate # (This puts the function variables into memory.)
currentInterrogationVariables="${interrogationVariables}" # The variable interrogationVariables contains a list of all function variables available for interrogation.
for currentInterrogationVariable in ${currentInterrogationVariables}; do
echo "content of ${currentInterrogationVariable}:"
eval "echo ${${currentInterrogationVariable}}"
done
done
再次感谢您的任何想法!
【问题讨论】:
-
似乎间接是最明智的方法(有关详细信息,请参阅答案)。这是我想出的另一种方法: currentInterrogationVariableValue="$(eval "echo \"\${${currentInterrogationVariable}}\"")"
标签: bash function variables metadata