如何在将标准输出重定向到 Bash 中的文件时添加时间戳? [英] How to add timestamp while redirecting stdout to file in Bash?

查看:24
本文介绍了如何在将标准输出重定向到 Bash 中的文件时添加时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序(服务器),我正在寻找一种方法(脚本),可以将其所有 stdout 重定向(或更好地复制)到文件并为每个条目添加时间戳.

I have a program (server) and I am looking for a way (script) that will redirect (or better duplicate) all its stdout to file and add timestamp for each entry.

我已经做了一些研究,我能得到的最远的结果要归功于 如何将时间戳添加到 STDERR 重定向.它重定向 stdout 但添加的时间戳是脚本完成的时间:

I've done some research and the furthest I could get was thanks to How to add timestamp to STDERR redirection. It redirects stdout but the timestamp added is of the time when the script finishes:

#!/bin/bash
./server | ./predate.sh > log.txt

predate.sh 的代码:

#!/bin/bash
while read line ; do
    echo "$(date): ${line}"
done

似乎在退出程序后会刷新服务器输出.(无需重定向即可正常工作).此外,如果我尝试在提到的线程中的给定示例上使用 predate.sh ,它可以完美运行.我知道向主程序添加时间戳很容易,但我宁愿避免编辑其代码.

It seems that server output is flushed after exit of the program.(without redirecting it works fine). Also if I try using predate.sh on given example in mentioned thread, it works perfectly. I am aware it would be easy adding a timestamp to the main program but I would rather avoid editing its code.

推荐答案

我最近正好需要:在串行控制台 (picocom) 中接收日志消息,将它们打印到终端和文件,并在前面加上日期.

I recently needed exactly that: receive log messages in a serial console (picocom), print them to a terminal and to a file AND prepend the date.

>

我现在使用的看起来很糟糕.像这样:

What I now use looks s.th. like this:

picocom -b 115200 /dev/tty.usbserial-1a122C | awk '{ print strftime("%s: "), $0; fflush(); }' | tee serial.txt

  • picocom 的输出通过管道传送到 awk
  • awk 将日期放在前面(%s 选项将时间转换为 自 1970-01-01 00:00:00 UTC 以来的秒数 - 或者使用 %c 作为人类可读的格式)
  • fflush() 刷新任何缓冲输出awk
  • 通过管道传送到 tee 将它转移到一个文件中.(你可以找到一些关于 tee 此处)
    • the output of picocom is piped to awk
    • awk prepends the date (the %s option converts the time to the Number of seconds since 1970-01-01 00:00:00 UTC - or use %c for a human-readable format)
    • fflush() flushes any buffered output in awk
    • that is piped to tee which diverts it to a file. (you can find some stuff about tee here)
    • 这篇关于如何在将标准输出重定向到 Bash 中的文件时添加时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆