如何将stdout重定向到Bash中的文件时添加时间戳? [英] How to add timestamp while redirecting stdout to file in 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
- the output of
picocom
is piped toawk
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 inawk
- that is piped to
tee
which diverts it to a file. (you can find some stuff abouttee
here)
这篇关于如何将stdout重定向到Bash中的文件时添加时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- the output of
tee
的