启动在bash shell脚本动态变量(可变变量) [英] Initiating dynamic variables (variable variables) in bash shell script
问题描述
我是通过bash shell中使用PHP CLI。请查看<一个href=\"http://stackoverflow.com/questions/4377191/manipulating-an-array-printed-by-php-cli-in-shell-script\">Manipulating在shell脚本数组(通过PHP-CLI印刷)了解详情。
I am using PHP CLI through bash shell. Please check Manipulating an array (printed by php-cli) in shell script for details.
在下面的shell code我能够呼应键
- ,我得到的值
对从PHP脚本。
In the following shell code I am able to echo the key
- value
pairs that I get from the PHP script.
IFS=":"
# parse php script output by read command
php $PWD'/test.php' | while read -r key val; do
echo $key":"$val
done
以下是输出这一点 -
Following is the output for this -
BASE_PATH:/path/to/project/root
db_host:localhost
db_name:database
db_user:root
db_pass:root
现在我只想启动动态变量while循环中,这样我可以像 $ BASE_PATH
使用它们有值/路径/到/项目/根'
, $ DB_HOST
有'localhost'的
Now I just want to initiate dynamic variables inside the while loop so that I can use them like $BASE_PATH
having value '/path/to/project/root'
, $db_host
having 'localhost'
我来自一个PHP的背景。我想类似 $$键= $ VAL
的PHP
I come from a PHP background. I would like something like $$key = $val
of PHP
推荐答案
您可以尝试使用评估
结构中的 BASH :
You may try using the eval
construct in BASH:
key="BASE_PATH"
value="/path/to/project/root"
# Assign $value to variable named "BASE_PATH"
eval ${key}="${value}"
# Now you have the variable named BASE_PATH you want
# This will get you output "/path/to/project/root"
echo $BASE_PATH
然后,就用它在你的循环。
Then, just use it in your loop.
编辑:这读取循环的创建一个子shell 的,不会让你使用它们的循环之外。您可能会重构读取循环,使子shell不创建:
this read loop creates a sub-shell which will not allow you to use them outside of the loop. You may restructure the read loop so that the sub-shell is not created:
# get the PHP output to a variable
php_output=`php test.php`
# parse the variable in a loop without creating a sub-shell
IFS=":"
while read -r key val; do
eval ${key}="${val}"
done <<< "$php_output"
echo $BASE_PATH
这篇关于启动在bash shell脚本动态变量(可变变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!