我是 shell 脚本的新手,今天学到了很多东西。 这是这个问题的扩展 Assigning values printed by PHP CLI to shell variables
我找到了在我的 shell 脚本中读取变量的解决方案。现在如何操作数组?如果我在我的 PHP 代码中准备一个数组并打印它,并在我的 shell 中回显,它会显示 Array。如何在 shell 脚本中访问该数组?我尝试了 how to manipulate array in shell script 中给出的解决方案
使用以下代码:-
PHP代码
$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 代码
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
我得到这个输出:-
Array - 0
- 1
- 2
- 3
- 4
而我想得到这个:-
Array
BASE_PATH - /path/to/project
db_host - localhost
db_name - database
db_user - root
db_pass - root
最佳答案
您应该首先调试您的PHP 脚本 以生成有效的数组内容、代码
print $associativeArray;
只会得到以下输出:
$ php test.php
Array
您可以简单地在 foreach 循环中打印关联数组:
foreach ( $associativeArray as $key=>$val ){
echo "$key:$val\n";
}
给出一个由':'分隔的变量名+内容列表
$ php test.php
BASE_PATH:1
db_host:2
db_name:3
db_user:4
db_pass:5
至于 shell 脚本,我建议使用简单易懂的 shell 结构,然后使用高级脚本(如 ${#result}
)以正确使用它们。
我已尝试使用以下 bash 脚本将变量从 PHP 脚本输出获取到 shell 脚本:
# 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
关于linux - 在 shell 脚本中操作数组(由 php-cli 打印),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377191/