2012-10-15 32 views
0

我是新的shell腳本,並試圖讓所有的android設備在一個數組,但我的數組是空的,當功能完成。殼 - 獲取Android設備到陣列

#!/bin/bash 

declare -a arr 
let i=0 

MyMethod(){ 
    adb devices | while read line #get devices list 
    do 
    if [ ! "$line" == "" ] && [ `echo $line | awk '{print $2}'` == "device" ] 
    then 
     device=`echo $line | awk '{print $1}'` 
     echo "Add $device" 
     arr[$i]="$device" 
     let i=$i+1 
    fi 
    done 

echo "In MyMethod: ${arr[*]}" 
} 

################# The main loop of the function call ################# 

MyMethod 
echo "Not in themethod: ${arr[*]}" 

arr - 是空的,我做錯了什麼?

感謝您的諮詢。

回答

0

您可能會遇到的問題是,管道命令導致它在子外殼中運行,並且在那裏更改的變量不會傳播到父外殼。你的解決方案可能會是這樣的:

adb devices > devices.txt 
while read line; do 
    [...] 
done < devices.txt 

,我們輸出保存到一箇中間文件,然後被裝入while循環,也許使用bash的語法命令的輸出存入中介臨時文件:

while read line; do 
    [...] 
done < <(adb devices) 

所以腳本變爲:

#!/bin/bash 

declare -a arr 
let i=0 

MyMethod(){ 
    while read line #get devices list 
    do 
    if [ -n "$line" ] && [ "`echo $line | awk '{print $2}'`" == "device" ] 
    then 
     device="`echo $line | awk '{print $1}'`" 
     echo "Add $device" 
     arr[i]="$device" # $ is optional 
     let i=$i+1 
    fi 
    done < <(adb devices) 

echo "In MyMethod: ${arr[*]}" 
} 

################# The main loop of the function call ################# 

MyMethod 
echo "Not in themethod: ${arr[*]}" 

一些額外的意見:

  1. 爲了避免錯誤,我建議你用雙引號括住後面的引號。
  2. 美元是arr[$i]=
  3. 可選沒有爲空字符串特定測試:[ -z "$str" ]檢查,如果字符串爲空(零長度)和[ -n "$str"]檢查,如果它不是

希望這有助於= )

+0

太棒了!非常感謝。 – AlexMrKlim