Array manipulation (printed by php-cli) in a shell script

I am new to shell scripting and today I learned a lot. This is the extension for this question. Assigning Values โ€‹โ€‹Printed by PHP CLI for Shell Variables

I got a solution to read a variable in my shell script. Now how to manipulate an array? If I prepare the array in my PHP code and print it, and echo in my shell, it will display Array. How to access this array in a shell script? I tried the solution given in how to manipulate an array in a shell script

With the following code: -
Php code

$neededConstants = array("BASE_PATH","db_host","db_name","db_user","db_pass"); $associativeArray = array(); foreach($neededConstants as $each) { $associativeArray[$each] = constant($each); } print $associativeArray; 

Shell code

 function getConfigVals() { php $PWD'/developer.php' } cd .. PROJECT_ROOT=$PWD cd developer # func1 parameters: ab result=$(getConfigVals) for((cnt=0;cnt<${#result};cnt++)) do echo ${result[$cnt]}" - "$cnt done 

I get this conclusion: -

 Array - 0 - 1 - 2 - 3 - 4 

While I want to get this: -

 Array BASE_PATH - /path/to/project db_host - localhost db_name - database db_user - root db_pass - root 
+1
source share
3 answers

First you must debug the PHP script to create valid array content, the code

 print $associativeArray; 

just you get the following result:

 $ php test.php Array 

You can simply print the associative array in a foreach loop:

 foreach ( $associativeArray as $key=>$val ){ echo "$key:$val\n"; } 

containing a list of variable names + content separated by a ':'

 $ php test.php BASE_PATH:1 db_host:2 db_name:3 db_user:4 db_pass:5 

As for the shell script , I suggest using simple and straightforward shell constructs, and then move on to advanced ones (for example, ${#result} ) to use them correctly.

I tried the following bash script to get variables from a php script output to shell script:

 # set the field separator for read comand IFS=":" # parse PHP  output by read command php $PWD'/test.php' | while read -r key val; do echo "$key = $val" done 
+2
source

With bash4, you can use mapfile to populate the array and replace the process to feed it:

 mapfile -t array < <( your_command ) 

Then you can go through the array with:

 for line in "${array[@]}" 

Or use indexes:

 for i in "${#array[@]}" do : use "${array[i]}" done 
+2
source

You do not say which shell you use, but assume that it supports arrays:

 result=($(getConfigVals)) # you need to create an array before you can ... for((cnt=0;cnt<${#result};cnt++)) do echo ${result[$cnt]}" - "$cnt # ... access it using a subscript done 

This will be an indexed array, not an associative array. Although associative arrays are supported in Bash 4, you will need to use a loop similar to Martin Kosek's response loop for assignment if you want to use them.

0
source

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


All Articles