【问题标题】:How to timestamp each line of a UNIX command that streams to stdout?如何为流到标准输出的 UNIX 命令的每一行加上时间戳?
【发布时间】:2016-08-30 05:00:22
【问题描述】:

假设我想为ping google.com 之类的命令添加时间戳,以便输出看起来像

[9:48:56]PING google.com (116.28.94.14): 56 data bytes
[9:48:55]64 bytes from 116.28.94.14: icmp_seq=0 ttl=54 time=13.118 ms
[9:48:57]64 bytes from 116.28.94.14: icmp_seq=1 ttl=54 time=13.943 ms
[9:48:58]64 bytes from 116.28.94.14: icmp_seq=2 ttl=54 time=19.103 ms
[9:48:59]64 bytes from 116.28.94.14: icmp_seq=3 ttl=54 time=12.854 ms

我已经研究过使用管道和命令(如 xargawk)的奇特方式,但我就是无法做到这一点。另外,假设我的环境不允许我使用像stdbuffunbuff 这样的花哨的东西。如果可能的话,用最类似unix的方法来实现这一点会很棒。谢谢!

【问题讨论】:

  • man ping 说有一个选项 -D.. 检查它有帮助
  • 你没有使用管道和awk的“奇葩方式”是什么?我通常对perl -ne 'printf "[%s]: %s", scalar(localtime), $_'很满意

标签: unix command-line stdout unix-timestamp


【解决方案1】:

这是最简单和最愚蠢的方法:

$ while read -r line ; do echo "$(date "+%H:%M:%S"): $line" ; done < <(while true ; do echo foo ; sleep 1 ; done)
00:07:08: foo
00:07:09: foo
00:07:10: foo
00:07:11: foo
00:07:12: foo

您可以根据需要格式化时间戳并运行您想要的任何命令:

$ while read -r line ; do echo "$(date "+%s"): $line" ; done < <(ping google.com)
1472533833: PING google.com (216.58.216.78): 56 data bytes
1472533833: 64 bytes from 216.58.216.78: icmp_seq=0 ttl=55 time=11.391 ms
1472533834: 64 bytes from 216.58.216.78: icmp_seq=1 ttl=55 time=12.746 ms
1472533835: 64 bytes from 216.58.216.78: icmp_seq=2 ttl=55 time=10.912 ms
1472533836: 64 bytes from 216.58.216.78: icmp_seq=3 ttl=55 time=13.065 ms
1472533837: 64 bytes from 216.58.216.78: icmp_seq=4 ttl=55 time=10.684 ms

这里是一个shell函数:

function logger {
  while read -r line ; do
    echo "$(date "+%H:%M:%S"): $line"
  done < <($*)
}

奇怪的命令和命令输出可能会破坏它,因此可能需要进行一些额外的调整,但希望这对您来说是一个好的开始。

编辑:一些快速的谷歌搜索会出现一个带有一些很好答案的线程here

【讨论】:

  • 您可以将$line 偷运到date 格式字符串中;只需将百分号加倍即可避开任何百分号。 date +"%T: ${line//%/%%}"
【解决方案2】:

moreutils1 中的 ts 命令(用于“时间戳”)正是为此而设计的。要将时间戳添加到ping 输出格式,如您的示例,您可以使用

ping google.com | ts '[%H:%M:%S]'

我不知道这是否属于“使用管道的奇特方式”,但我会说这是一种很好的 unix 方式,因为您使用的是does one thing and does it well 的工具.

1您可以在 Debian/Ubuntu 中安装 moreutils,例如使用sudo apt-get install moreutils

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2015-06-01
    • 1970-01-01
    • 2015-04-25
    • 2023-03-20
    • 2017-02-25
    相关资源
    最近更新 更多