无法满足shell脚本中的if条件

Amr*_*mel 0 linux bash shell-script adb

我试图在下面执行以下 shell 脚本

function Check_Status () {

       if [[ "$(adb shell getprop sys.boot_completed)" =~ "adb: no devices/emulators found" ]]; 
       then
          echo "here"

       else 
            echo "im here"
       fi;
};

Check_Status
Run Code Online (Sandbox Code Playgroud)

我得到以下输出,我期待看到“这里”而不是“我在这里”

截屏

不确定会丢失什么

ilk*_*chu 6

你图片上的文字看起来和你脚本中的一样,是的。但仅凭一张照片很难确定。

但是请注意,当您运行脚本时,文本是如何进入终端的?命令替换应该捕获输出,无论它捕获什么,都不会打印。adb可能将该消息打印到标准错误,而不是标准输出,因此它不会被捕获。

你可以用这样的东西来验证:

echo "running the command substitution... (errors would print after this line)"
output=$(adb shell getprop sys.boot_completed)
echo "captured output (stdout): '$output'"
Run Code Online (Sandbox Code Playgroud)

然后看看什么地方出来的。

如果这确实是问题所在,那么您需要在命令替换中将 stderr 重定向到 stdout:

if [[ "$(adb shell getprop sys.boot_completed 2>&1)" =~ "adb: no devices/emulators found" ]]; then
    ...
Run Code Online (Sandbox Code Playgroud)