linux - 在 Linux 中输出中的关键字后终止命令

标签 linux bash ubuntu

如果某个关键字显示在命令的输出中,我想发送一个 SIGKILL。例如,如果发出以下命令:

ubuntu@ip-172-31-24-250:~$ ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=109 time=0.687 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=109 time=0.704 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=109 time=0.711 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=109 time=0.809 ms
64 bytes from 8.8.8.8: icmp_seq=5 ttl=109 time=0.727 ms
64 bytes from 8.8.8.8: icmp_seq=6 ttl=109 time=0.835 ms
^C
看到输出后 "icmp_seq=6"我希望命令自动停止。我知道 平 8.8.8.8 -c 6 将产生相同的结果,但这仅用于示例。

最佳答案

请您尝试以下方法:

#!/bin/bash

ping 8.8.8.8 | while IFS= read -r line; do
    echo "$line"
    [[ $line =~ icmp_seq=6 ]] && kill -9 $(pidof ping)
done

关于linux - 在 Linux 中输出中的关键字后终止命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72166332/

相关文章:

Java Sound API - 如何获取麦克风设备信息?

c++ - QT Creator——跨平台编译

linux - 32位Linux汇编代码

bash - 使用 shell 脚本将有符号整数转换为无符号整数

bash - 在bash文件中运行docker命令并使用crontab运行

c++ - 如何在 Ubuntu 和 C/C++ 下拔出 USB 设备而不重新启动

python - 无法通过 Python 从 Ubuntu 上的 Gmail 发送电子邮件

linux - 错误 : Expected one of#, input, filter, output at line 34, column 1 (byte 1) after {:level=>:error} in logstash

bash - 在 Bash 中使用一个变量来引用另一个变量

c - 在 unix 架构中,与 c 相关的 POSIX 的用途是什么