如果某個關鍵字顯示在命令的輸出中,我想發送一個 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會產生相同的結果,但這只是示例。
uj5u.com熱心網友回復:
請您嘗試以下方法:
#!/bin/bash
ping 8.8.8.8 | while IFS= read -r line; do
echo "$line"
[[ $line =~ icmp_seq=6 ]] && kill -9 $(pidof ping)
done
uj5u.com熱心網友回復:
一種方法是將命令輸出重定向到檔案,然后grep為所需的特定字串設定到檔案的回圈。如果grep成功,則結束回圈并終止行程。這樣的腳本ping可能如下所示:
這有一個錯誤
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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/471553.html
