【问题标题】:How to pipe tail -f output into the shell script如何将 tail -f 输出通过管道传输到 shell 脚本中
【发布时间】:2021-08-29 07:39:00
【问题描述】:

我想通过这个脚本使用 Telegram bot 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

但它不发送输出。

【问题讨论】:

  • 你想达到什么目的?在每个新的日志行上发送一条消息?
  • @MarcoLucidi 是的,正是这个
  • 你应该处理每个传入的行。目前,我认为您的脚本仍然停留在TEXT=$(tee) 等待stdin 结束/关闭,但它永远不会发生,因为tail -f 保持打开状态。
  • @MarcoLucidi 我应该使用循环吗?能举个例子吗?
  • 是的循环,我正在写一个例子

标签: bash tail


【解决方案1】:

您的脚本仍然停留在该行

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
$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 2011-07-17
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多