Manipulating an array (printed by php-cli) in shell script
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 solution to read a variable in my shell script. Now how to manipulate an array? If I prepare an array in my PHP code and print it, and echo in my shell, it displays Array. How to access that array in the shell script? I tried the solution given in how to manipulate array in shell script
With the following code:-
PHP code$neededConstants = array("BASE_PATH","db_host","db_name","db_user","db_pass");
$associativeArray = array();
foreach开发者_Go百科($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: a b
result=$(getConfigVals)
for((cnt=0;cnt<${#result};cnt++))
do
echo ${result[$cnt]}" - "$cnt
done
I get this output:-
Array - 0
- 1
- 2
- 3
- 4
Whereas I want to get this:-
Array
BASE_PATH - /path/to/project
db_host - localhost
db_name - database
db_user - root
db_pass - root
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.
精彩评论