gpt4 book ai didi

bash - 为什么 ADB 命令会中断 bash 脚本循环?

转载 作者:行者123 更新时间:2023-11-29 08:54:41 25 4
gpt4 key购买 nike

当从 shell 脚本循环运行多个 adb 命令时,我注意到一个问题,大多数命令都不会执行。

这是一个示例脚本。

脚本名称:adbscript.sh:

#!/bin/bash

devicecount=0
while read device; do
((devicecount++))
serialno="NA"
appinstallcount="NA"
echo "Processing Device #$devicecount: $device"
# serialno=$(adb -s $device shell getprop ro.serialno)
# appinstallcount=$(adb -s $device shell pm list packages | wc -l)
echo -e "Device: $device | Serialno: $serialno | Apps installed: $appinstallcount\n"
done < <(adb devices | egrep "\bdevice\b" | awk '{print $1}')
echo "Finished."

注释掉 adb 命令的输出

我连接了 5 台设备。当从没有 adb 命令的 bash 文件运行时,这是输出。它遍历 5 个循环中的每一个。

Processing Device #1: 192.168.15.93:5123Device: 192.168.15.93:5123 | Serialno: NA | Apps installed: NAProcessing Device #2: 192.168.15.95:5123Device: 192.168.15.95:5123 | Serialno: NA | Apps installed: NAProcessing Device #3: emulator-5554Device: emulator-5554 | Serialno: NA | Apps installed: NAProcessing Device #4: 31005c77c8cfb200Device: 31005c77c8cfb200 | Serialno: NA | Apps installed: NAProcessing Device #5: 98883837594d4f5453Device: 98883837594d4f5453 | Serialno: NA | Apps installed: NAFinished.

Output with loop containing ADB commands

When the adb shell command is uncommented it only properly iterates lines of the first loop. This is the output with the adb command uncommented:

Processing Device #1: 192.168.15.93:5123Device: 192.168.15.93:5123 | Serialno: 98883837594d4f5453 | Apps installed: 442Finished.

Can someone explain this behavior and what would have to be done to have all the lines and all the loops processed?

By the way, this is the output supplied to the script (one liner command and output):

$ adb devices | egrep "\bdevice\b" | awk '{print $1}'
192.168.15.93:5123
192.168.15.95:5123
emulator-5554
31005c77c8cfb200
98883837594d4f5453

最佳答案

adb shell 将 stdin 连接到设备上运行的命令,这通常会消耗 stdin 直到到达 EOF。因此,这些命令会消耗所有其余的设备名称,从而导致循环退出。

使用 stdin 重定向运行 adb,因此它们会立即得到 EOF,而不会弄乱您要循环的内容:

serialno=$(adb </dev/null -s $device shell getprop ro.serialno)
appinstallcount=$(adb </dev/null -s $device shell pm list packages | wc -l)

关于bash - 为什么 ADB 命令会中断 bash 脚本循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44634478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com