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



我想与社区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 命令?

为简单起见,我用ts替换了您的perl命令。 以下技巧不是完整的解决方案,但无论如何您都可能感兴趣。

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

$ 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 '33c'清除滚动缓冲区也不再有效。

以下命令将从.bashrc中启动bash | ts。将其粘贴到.bashrc的最后。由于提到的问题,我不会推荐它。

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

最新更新