Bash:循环处理进程输出并终止该进程

4

我需要在以下内容上提供帮助:

我使用Linux来编写命令并发送到设备。我需要向设备提交一个grep logcat命令,然后迭代它的输出,当正在生成的输出中查找特定字符串时。一旦找到这个字符串,我希望我的脚本移动到下一个命令。

伪代码如下:

for line in "adb shell logcat | grep TestProccess"
do 
    if "TestProccess test service stopped" in line:
       print line
       print "TestService finished \n"
       break
    else:
       print line
done
3个回答

5
adb shell logcat | grep TestProcess | while read line
do
  echo "$line"
  if [ "$line" = "TestProces test service stopped" ]
  then echo "TestService finished"
       break
  fi
done

1
adb shell logcat | grep -Fqm 1 "TestProcess test service stopped" && echo "Test Service finished"

grep标志:

  1. -F - 把字符串作为字面量处理,而不是正则表达式
  2. -q - 不要向标准输出打印任何内容
  3. -m 1 - 在第一次匹配后停止

&&后面的命令只有在grep找到匹配项时才会执行。只要您“知道”grep最终会匹配并希望无条件地继续执行,就可以省略&& ...


工作得非常好,非常感谢您的贡献,非常感激! - Nikl

0

你可以使用一个until循环。

adb shell logcat | grep TestProccess | until read line && [[ "$line" =~ "TestProccess test service stopped" ]]; do
 echo $line;
done && echo -n "$line\nTestService finished" 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接