【问题标题】:Shell - get android devices into arrayShell - 将android设备放入数组
【发布时间】:2012-10-15 22:01:22
【问题描述】:
我是 shell 脚本的新手,我正在尝试将所有 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 - 是空的,我做错了什么?
感谢您的建议。
【问题讨论】:
标签:
android
bash
shell
sh
【解决方案1】:
您可能的问题是管道命令会导致它在子 shell 中运行,并且在那里更改的变量不会传播到父 shell。你的解决方案可能是这样的:
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[*]}"
一些额外的观察:
- 为避免错误,我建议您用双引号将后引号括起来。
-
arr[$i]= 中的美元是可选的
- 对空字符串有一个特定的测试:
[ -z "$str" ] 检查字符串是否为空(零长度),[ -n "$str"] 检查是否不是
希望这会有所帮助 =)