Manipulating an array (printed by php-cli) in shell script

前端 未结 3 1614
情深已故
情深已故 2021-01-23 14:54

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

3条回答
  •  一生所求
    2021-01-23 15:39

    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
    

提交回复
热议问题