我已经搜索过这个并希望找到数百个解决方案,但没有找到!
我想读取 STDOUT 流并等待特定字符串出现,而不等待进程完成。
我现在所拥有的,等待过程完成后再返回输出:
RESP=$(execute some command 2>&1)
if $RESP contains something then do something;
如何实时读取流而不是等待它完成?
我尝试了 Paddy 建议的以下方法,用于测试与 ping 命令的配合:
RESP=$(ping 192.168.0.1 | grep seq=5 -m1)
但是它不适用于我想使用 dhcpcd 的命令:
RESP=$(dhcpcd wlan0 -r 192.168.0.190 | grep claims -m1)
与 ping 测试不同,命令的输出被发送到控制台而不是被隐藏,并且它永远不会检测到“声明”文本,即使它出现在输出中?
您可以通过管道进入
grep
进行匹配,并在遇到匹配时让它退出。这也将退出产生输出的程序。
if mycommand | grep something -q; then
dosomething
fi
如果有任何匹配,上面将退出(
-q
),但不显示结果。如果您想查看输出,可以在第一场比赛时退出(使用 -m1
):
RESP=$(mycommand | grep something -m1)
阅读
grep
的手册页以获取更多信息。
如果您不想取消产生输出的程序,您可以尝试将其写入后台文件,然后
tail
该文件:
mycommand > output &
if tail -f output | grep something -q; then
dosomething
fi
从 this unix.stackexchange 答案我得到了以下解决方案:
cmd_which_streams_new_lines \
| while read -r line; do
# process your line here
echo "${line}"
# when you're done, break the loop (be prepared for messy stderr)
done
watch example_command | grep hello_example -q
对于读取标准输出,我认为使用 shell 不是明智的选择。
它可能几乎不能用这个。