如何将 tail -f 输出通过管道传输到 shell 脚本

How to pipe tail -f output into the shell script

我想通过此脚本使用电报机器人 api 监控服务器日志:

#!/bin/bash
CHATID="id"
KEY="key"
TIME="10"
URL="https://api.telegram.org/bot$KEY/sendMessage"
TEXT=$(tee)

curl -s --max-time $TIME -d "chat_id=$CHATID&disable_web_page_preview=1&text=$TEXT" $URL >/dev/null

然后使用管道将日志输出到脚本:

tail -f /var/log/my.log | ./telegram_log.sh

但它不发送输出。

您的脚本仍然卡在行

TEXT=$(tee)

因为 tee 它正在等待 stdin 关闭,但它永远不会发生,因为 tail -f 保持打开以“跟随”文件。

要在每个新日志行上发送消息,您应该处理每个传入行而不是等待整个 stdin。一个简单的 while read 就可以做到,例如:

$ more bot.sh
#!/bin/sh

while IFS= read -r line; do
        echo send new line as msg: "$line"
        # TODO here goes curl etc...
done
$ touch log
$ tail -f log | ./bot.sh
send new line as msg: hello
send new line as msg: world
send new line as msg: goodbye

我在另一个终端上做了:

$ echo hello >> log
$ echo world >> log
$ echo goodbye >> log
$