仅使用 tee 和 ts 将时间戳添加到日志文件

Prepend timestamp to logfile only using tee and ts

以下代码片段为 stdout 和 stderr 添加了一个时间戳,其中的字符串略有不同。那不是我想要的。必须如何修改才能仅将时间戳添加到日志文件,并按原样将输出保持在屏幕上?

LOGFILE=/var/log/a.log
exec 1> >(stdbuf -e0 -o0 ts '[%F %T] O:' | tee -a "$LOGFILE") \
     2> >(stdbuf -e0 -o0 ts '[%F %T] E:' | tee -a "$LOGFILE" >&2)

使用进程替换 tee 参数,而不是直接使用文件。示例:

#!/bin/bash
cat file | tee >(ts >> log.txt)
> bash test.sh
test1
test2
> cat log.txt
Oct 22 19:34:33 test1
Oct 22 19:34:33 test2

在您的示例中,您首先将输出重定向到 ts,然后再重定向到 tee,因此您也会在控制台中获得时间戳。