2010-12-07 35 views
1

我是一名帶shell腳本的新手,今天我學到了很多東西。 這是此問題的擴展Assigning values printed by PHP CLI to shell variables在shell腳本中操作數組(由php-cli打印)

我得到了解決方案來讀取我的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 

回答

2

你應該調試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 

至於外殼腳本,我建議使用簡單易懂的殼結構,然後進入高級(如${#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 
+0

感謝和+1建議首先使用簡單和可理解的shell構造,然後到達advan ced的人 – 2010-12-08 07:31:30

0

你不說你正在使用,但假設它是一個支持數組什麼殼:這是一個索引數組,而不是關聯數組。雖然在Bash 4中支持關聯數組,但如果要使用它們,則需要使用與Martin Kosek的分配答案類似的循環。

+0

我正在使用linux bash shell – 2010-12-08 07:32:48

2

隨着bash4,您可以使用映射文件來填充數組和工藝替代餵它:

mapfile -t array < <(your_command) 

然後你可以通過陣列:

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

或者使用索引:

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