如果脚本通过管道传输到 bash,则 adb 会出现奇怪的行为

strange adb behaviour if script is piped into bash

我偶然发现了一个我无法解释的奇怪行为。我试图缩小问题范围。我有以下测试 testscript.sh 脚本:

echo before
adb shell ls
echo after

如果我 运行 使用 bash -x testscript.sh 的脚本,一切都按预期工作,我得到以下输出:

+ echo before
before
+ adb shell ls
acct
bin
bugreports
...
sdcard
storage
sys
system
ueventd.rc
vendor
+ echo before
before

但是如果我 运行 将脚本作为带有 cat testscript.sh | bash -sx 的管道脚本,我会得到以下输出:

+ echo before
before
+ adb shell ls
acct
bin
bugreports
...
sdcard
storage
sys
system
ueventd.rc
vendor

最后的echo after没有执行,我也想不通为什么。该脚本 运行ning 在 Ubuntu 服务器 18.04 上。 adb 是官方 Ubuntu 包中的那个。

$ adb --version
Android Debug Bridge version 1.0.39
Version 1:8.1.0+r23-5~18.04
Installed as /usr/lib/android-sdk/platform-tools/adb
$ bash --version
GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)

有人能给我启发吗,这里发生了什么。

当您 运行 使用 bash scriptname 脚本时,所有命令的标准输入仍然 运行s 连接到终端。所以 adb 将从终端读取其标准输入。

当您重定向 bash 的输入时,此重定向被 adb 继承。除非你对 adb shell 使用 -n 选项,否则它将从标准输入读取额外的输入并将其发送到远程系统作为你 运行 命令的可能输入(它不知道ls 不读取标准输入)。

改为

adb shell -n ls