开发者

Initiating dynamic variables (variable variables) in bash shell script

开发者 https://www.devze.com 2023-01-29 15:50 出处:网络
I am using PHP CLI through bash shell. Please check Manipulating an array (printed by php-cli) in shell script for details.

I am using PHP CLI through bash shell. Please check Manipulating an array (printed by php-cli) in shell script for details.

In the following shell code I am able to echo the key- value pairs that I g开发者_开发百科et 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

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'

I come from a PHP background. I would like something like $$key = $val of PHP


Using eval introduces security risks that must be considered. It's safer to use declare:

# parse php script output by read command
while IFS=: read -r key val; do
    echo $key":"$val
    declare $key=$val
done < <(php $PWD'/test.php')

If you are using Bash 4, you can use associative arrays:

declare -A some_array
# parse php script output by read command
while IFS=: read -r key val; do
    echo $key":"$val
    some_array[$key]=$val
done < <(php $PWD'/test.php')

Using process substition <() and redirecting it into the done of the while loop prevents the creation of a subshell. Setting IFS for only the read command eliminates the need to save and restore its value.


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.


EDIT: 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
0

精彩评论

暂无评论...
验证码 换一张
取 消