背景
做为安卓开发工程师,adb 是使用频率非常高的调试工具,但是当电脑连接了多个 android 手机或虚拟机设备后,每次使用 adb 都需要通过 -s 参数手动指定调试哪个设备,输入繁琐。例如:
adb -s E0014021600090 logcat
可能有人会说,可以断开暂时不想调试的设备,每次保证只连接一个调试的设备。但是在需要频繁多个设备间调试的场景下,该操作还是比较麻烦的。
此时,就非常希望在我们输入 adb 命令时,如果存在多个设备,则提示我们选择哪个设备(输入简单的设备序号)进行调试,无须输入冗长的设备序列号参数,也不用频繁的插拔数据线。
脚本实现
为此写了个 adb 的封装脚本(仅支持 mac 和 linux 系统):
#!/bin/bash
export PATH
#使用前请先配置本地 adb 的路径
user=`whoami`
adb="/Users/$user/Library/Android/sdk/platform-tools/adb"
if [ ! -f $adb ]; then
echo "adb 路径配置有误,请修正该脚本中 adb 的路径"
exit 1
fi
#部分 adb 参数不需要选择具体某个设备的白名单列表
whiteList=(
devices
connect
disconnect
start-server
kill-server
help
version
pair
forward
reverse
)
if [[ "$@" == "" ]]; then
"$adb" "$@"
exit $?
fi
if [[ "${whiteList[@]}" =~ "$1" ]]; then
"$adb" "$@"
exit $?
fi
if [[ $1 == "-s" ]]; then
"$adb" "$@"
exit $?
fi
devices=`$adb devices | sed -n '2,$p' | cut -d ' ' -f 1`
count=`echo "$devices" | wc -l | xargs`
if [ $count -gt 1 ]; then
i=1
hint="N0.\tSN (Device)"
while(($i<="$count"));do
device=`echo "$devices" | sed -n "${i}p"`
info=`adb devices | grep $device | cut -d ' ' -f 2`
if [ $info == "device" ]; then
brand=`timeout 1 $adb -s $device shell getprop ro.product.brand 2> /dev/null || echo "error: timeout"`
model=`timeout 1 $adb -s $device shell getprop ro.product.model 2> /dev/null`
hint=$hint"\n[$i]\t$device ($brand $model)"
else
hint=$hint"\n$i\t$device (error: $info)"
fi
i=$(($i+1))
done
hint=$hint"\n---------------------------"
msg=`echo -e $hint`
read -n1 -p "${msg} `echo $'\n '`选择要调试的设备序号[1-$count]: " ID
echo -e '\n'
# 检查 ID 是否为合法数字
expr $ID "+" 1 &> /dev/null
if [ $? -ne 0 ];then
echo "请输入有效的设备序号[1-$count]"
exit 1
fi
if [ $ID -lt 1 -o $ID -gt $count ]; then
echo "请输入有效的设备序号[1-$count]"
exit 1
fi
device=`echo "$devices" | sed -n "${ID}p"`
"$adb" "-s" $device "$@"
else
"$adb" "$@"
fi
使用说明
步骤一:脚本中的 adb 路径变量需要修改成本地的 adb 路径,如果你之前配置过 adb 的环境变量,可以快速通过命令获知。
which adb
步骤二:将脚本命名为 adb 保存到某个具体路径,比如主用户目录下的 shells 目录(~/shells),给该文件新增可执行权限:
chmod a+x ~/shells/adb
步骤三:将该路径添加到环境变量配置文件~/.bashrc 或者~/.zshrc(如果使用 zsh) 中,比如
export PATH=/Users/luliang/shells:$PATH
此外,如果之前配置过 adb 路径,需要去掉之前的环境变量配置。保证执行 adb 时运行的是脚本文件。
接下来就可以像平时使用 adb 一样,来运行这个脚本了。当少于2个 android 设备连接时,运行效果跟平时的 adb 一样,当有多个设备时,会提示选择使用哪个设备进行调试。
运行效果
以 adb logcat 为例:
$ adb logcat
N0. SN (Device)
1 988d50414347355443 (samsung SM-G9500)
2 E0014021600090 (smartisan yq601)
---------------------------
选择要调试的设备序号[1-2]: 2
为方便区分不同的设备,设备列表的序列号后面还提供了设备品牌和型号。
同样,其他的 adb 命令 adb shell, adb reboot, adb install xxx.apk 等也是如此,只需要输入指定调试的设备序号,会自动执行类似 adb -s {SN} xxx 的命令,大大提高了多设备的调试效率。