gpt4 book ai didi

linux shell脚本在第一行后停止

转载 作者:太空狗 更新时间:2023-10-29 11:11:43 28 4
gpt4 key购买 nike

我尝试基于 MQTT 主题执行 etherwake。如果我在 while 语句中通过管道传输 mosquitto_sub 的输出将停止。

作品:

# mosquitto_sub -L mqtt://... | grep -o -E '([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}'
00:00:00:00:de:ad
00:00:00:00:be:ef
00:00:00:00:ca:fe
(goes on and on)

不起作用:

mosquitto_sub -L mqtt://... \
| grep -o -E '([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}' \
| hexdump

单行后输出停止:

0000000 1234 5678 9abc def0 abcd cafe 3762 3a65

大图是这样的:

mosquitto_sub -L mqtt://... \
| grep -o -E '([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}' \
| while read macaddr; do
echo "send WOL to " $macaddr;
/usr/bin/etherwake -D -b "$macaddr" 2>&1;
done

通常我对 Linux shell 没问题,但这次它只是卡在第一行之后。

我的猜测是 stdin 或 stdout 存在某种问题(未读取或已满等)。但我没有想法。

顺便说一句,它是一个 OpenWRT shell,所以是一个 ash 而不是 bash。

最佳答案

问题确实是 grep 与管道一起使用时的“缓冲”。

通常应该使用 '--line-buffered' 开关来强制 grep 逐行处理数据而不是缓冲数据。

因为 OpenWRT (busybox) 上的 grep 没有使用这个开关 'awk':

mosquitto_sub -L mqtt://... \
| awk '/([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}/{ print $0 }' \
| hexdump

如果没有使用 busybox 版本的 grep,解决方案如下:

mosquitto_sub -L mqtt://... \
| grep -o --line-buffered -E '([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}' \
| hexdump

非常感谢大家的帮助。

关于linux shell脚本在第一行后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57747533/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com