如何在bash脚本中使用变量变量名 [英] how to use variable variable names in bash script
问题描述
我正在尝试将一些php变量的值放入bash脚本中,以便设置其他bash变量.基本上,我需要能够访问变量的值-变量名.
I'm trying to get the values of some php variables into a bash script in order to set other bash variables. Basically I need to be able to access the value of a variable - variable name.
该脚本可以找到&读取文件,找到php变量,但是当我尝试设置它们时,它就挂了.这是我所拥有的:
the script can find & read the file, find the php variables, but when I try to set them it just hangs. Here is what I have:
variables=(database_user database_password dbase);
paths=(modx_core_path modx_connectors_path modx_manager_path modx_base_path);
for index in "${variables[@]}"; do
index=\$$index
echo $index;
$index="$(grep -oE '\$${!index} = .*;' $config | tail -1 | sed 's/$${!index} = //g;s/;//g')";
done
不知道我在这里做错了什么...
not sure what I am doing wrong here...
推荐答案
您正在尝试执行间接分配.
You are trying to perform an indirect assignment.
您应该摆脱这两行:
index=\$$index
echo $index;
只需编写:
echo "${!index}"
干净地进行间接扩展(为您提供名称包含在变量index
中的变量的值).
Which does an indirect expansion cleanly (gives you the value of the variable whose name is contained in variable index
).
接下来,问题所在的是这一行:
Next, the problematic line is this one:
$index="$(grep -oE '\$${!index} = .*;' ... (rest omitted)
在Bash中,分配不能以$
开头.
In Bash, an assignment cannot begin with a $
.
执行间接分配的一种方法是这种方式(按照上述建议删除index
重新分配后):
One way you can perform an indirect assignment is this (after removing the index
re-assignment as suggested above) :
printf -v "$index" "$(grep -oE '\$${!index} = .*;' ... (rest omitted)
这将使用printf
的-v
选项,这会将作为最终参数传递的值分配给变量,该变量的名称将传递给-v
选项.
This uses the -v
option of printf
, which causes the value passed as the final argument to be assigned to a variable, the name of which is passed to the -v
option.
还有其他处理间接分配/扩展的方法,其中一些具有代码注入风险,因为它们使用(可能不受控制的)数据作为代码.这是您可能需要进一步研究的东西.
There are other ways of handling indirect assignment/expansions, some with code injection risks, as they use (potentially uncontrolled) data as code. This is something you may want to research further.
请注意,我假设实际的grep
命令替换有效(我尚未测试).
Please note I am assuming the actual grep
command substitution works (I have not tested).
这篇关于如何在bash脚本中使用变量变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!