巴什 - 如何添加时间戳,而标准输出重定向到文件 [英] Bash - how to add timestamp while redirecting stdout to file

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

问题描述

我有一个程序(服务器)和我正在寻找一种方式(脚本)将重定向(或更好的副本)的所有标准输出到文件,并为每个条目添加时间戳。 I V做了一些研究和最远的我能得到多亏如何时间戳添加到STDERR重定向。它重定向标准输出,但增加的时间时间戳当脚本完成:

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. I v done some research and furthest I could get was thanks to How to add timestamp to STDERR redirection. It redirects stdout but add timestamp of time when the script finished:

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

predate.sh的code:

code of predate.sh:

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

我是初学Linux的,我显然失去了一些东西非常重要,因为它似乎在程序退出后,服务器输出被刷新。(没有重定向它工作正常)。另外,如果我尝试使用在提到线程给出的例子predate.sh,它完美地工作。我知道它会在probram可以轻松添加时间戳,但我宁愿避免编辑其code。

I am linux beginner and I am obviously missing something very important since it seems 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 work perfectly. I am aware it would be easy adding timestamp in the probram but i would rather avoid editing its code.

编辑:只工作答案在注释中。

the only working answers are in comments

推荐答案

我最近需要确切地指出:以串行控制台(picocom)接收日志消息,把它们打印到终端,到一个文件,prePEND日期

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.

我现在用看起来s.th.像这样的:

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 prepends的日期(%S 选项时转换为的号码几秒钟自1970-01-01 00:00:00 UTC 的 - 或使用%C 的可读格式)

  • fflush() 刷新任何缓冲输出 AWK

  • 被输送到 T恤它转移到一个文件中。 (你可以找到关于一些东西发球 here)

    • 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)
    • 这篇关于巴什 - 如何添加时间戳,而标准输出重定向到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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