如何在bash脚本中使用变量变量名 [英] how to use variable variable names in bash script

查看:373
本文介绍了如何在bash脚本中使用变量变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆