I am a newbie with shell scripts and I learnt a lot today. This is an extension to this question Assigning values printed by PHP CLI to shell variables
I got the solutio
You should debug your PHP script first to produce the valid array content, code
print $associativeArray;
will just get you the following output:
$ php test.php
Array
You can simply print the associative array in a foreach loop:
foreach ( $associativeArray as $key=>$val ){
echo "$key:$val\n";
}
giving a list of variable names + content separated by ':'
$ 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 understandable shell constructs and then get to the advanced ones (like ${#result}
) to use them correctly.
I have tried the following bash script to get the variables from PHP script output to shell script:
# set the field separator for read comand
IFS=":"
# parse php script output by read command
php $PWD'/test.php' | while read -r key val; do
echo "$key = $val"
done
With bash4, you can use mapfile to populate an array and process substitution to feed it:
mapfile -t array < <( your_command )
Then you can go through the array with:
for line in "${array[@]}"
Or use indices:
for i in "${#array[@]}"
do
: use "${array[i]}"
done
You don't say what shell you're using, but assuming it's one that 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 is going to be an indexed array, rather than an associative array. While associative arrays are supported in Bash 4, you'll need to use a loop similar to the one in Martin Kosek's answer for assignment if you want to use them.