Linux下输出关键字后终止命令



如果命令的输出中显示某个关键字,我想发送一个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">我希望命令自动停止。我知道ping 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

可以这样做的一种方法是将命令输出重定向到一个文件,然后为您想要的特定字符串设置一个到grep文件的循环。如果grep成功,则结束循环并杀死进程。ping的脚本可能如下所示:

这有一个BUG

ping www.google.com > output 2> error &
while [ true ]; do
grep "icmp_seq=6" output

if [ $? -eq 0 ]; then
break
fi
done
echo "sequence found, killing program"
pid=`pgrep ping` # get the PID of ping so we can kill it
kill -9 ${pid}

更新:我刚刚想到,这个脚本有一个缺点,如果搜索文本从未出现,它将无限运行(实际上,即使在候选程序终止后,它也会继续无限运行,或者程序在启动时立即死亡)。因此,这里有一个改进的脚本,它解释了所有这些:

ping www.google.com > output 2> error & # the & makes the command a background process so execution of other commands isn't blocked
pid=`pgrep ping`
while [ ! -z ${pid} ]; do # check if pid contains anything - if so, the ping command is still running
grep "icmp_seq=6" output

if [ $? -eq 0 ]; then
echo "sequence found, killing program"
kill -9 ${pid}
exit 0
fi
pid=`pgrep ping`
done
echo "Sequence not found"

优化更新:因为我对这些东西有强迫症,如果有很多输出,这个脚本就会陷入困境,因为grep必须筛选所有的输出。因此,我的优化建议是使用tail -1 output,然后通过管道将输出输出到grep,从而产生以下脚本:

ping www.google.com > output 2> error & # the & makes the command a background process so execution of other commands isn't blocked
pid=`pgrep ping`
while [ ! -z ${pid} ]; do # check if pid contains anything - if so, the ping command is still running
tail -1 output | grep "icmp_seq=6"

if [ $? -eq 0 ]; then
echo "sequence found, killing program"
kill -9 ${pid}
exit 0
fi
pid=`pgrep ping`
done
echo "Sequence not found"

最新更新