在命令输出的开头附加动态时间戳记

时间:2018-10-15 18:22:54

标签: bash

我想向bash社区检查是否有可能在命令输出的每一行之前打印动态时间戳记,甚至命令本身也需要一些时间来打印整个结果。这是示例:

在此,为便于说明,假设(echo hi; sleep 10; echo hello)作为单个CLI命令。它将在约10秒内打印整个结果(这可能会有所不同),其中包括多行输出,请注意下面的输出。当该行打印到屏幕上时,每行都有确切的时间戳。

(echo hi ;sleep 10 ;echo hello) |perl -nle 'print scalar(localtime), " ", $_'
Mon Oct 15 13:15:57 2018 hi
Mon Oct 15 13:16:07 2018 hello

查询:

所以,我的问题是:是否有可能以某种方式操纵bashrc或任何其他配置,而这将成为默认行为,而无需在每个命令上手动使用pipe和perl命令?

1 个答案:

答案 0 :(得分:1)

为简单起见,我将您的perl命令替换为ts。 以下技巧不是完整的解决方案,但是您可能还是有兴趣。

手动启动bash | ts,在新外壳中,所有命令输出都将带有时间戳。此类交互式会话的示例:

$ echo test
test
$ bash | ts
$ echo test
Oct 16 13:40:16 test
$ for i in a b c; do echo "$i"; sleep 1; done
Oct 16 13:41:38 a
Oct 16 13:41:39 b
Oct 16 13:41:40 c
$ exit
Oct 16 13:41:51
$ echo test
test

但是,在nano内时,像bash | ts这样的文本界面似乎不再起作用。同样,用printf '\033c'清除滚动缓冲区也行不通了。

以下命令将从您的bash | ts内部开始.bashrc。将其粘贴到.bashrc的最后。由于上述问题,我不推荐使用它。

bashParents="$(ps | grep -Fwc bash)"
(( bashParents-- )) # because of subshell $(...)
if (( bashParents <= 1 )); then
    bash | ts
fi
相关问题