Initiation of dynamic variables (variable variables) in a bash shell script

I am using PHP CLI through the bash shell. Please check Array Manipulation (printed by php-cli) in the shell script for details.

The following code shell I can track down a pair of key - value , which I get from a PHP script.

 IFS=":" # parse PHP  output by read command php $PWD'/test.php' | while read -r key val; do echo $key":"$val done 

Below 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, for example $BASE_PATH with value '/path/to/project/root' , $db_host with 'localhost'

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

+2
source share
2 answers

You can 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-wrapper that will not allow you to use them outside the loop. You can restructure the read cycle so that no sub-shell is 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 
+3
source

Using eval introduces security risks that need to be considered. It is safer to use declare :

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

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

 declare -A some_array # parse PHP  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 substitution <() and redirecting it to the done while prevents the creation of a subshell. Setting IFS for the read command only eliminates the need to save and restore its value.

+4
source

Source: https://habr.com/ru/post/918187/


All Articles