给tee输出加上时间戳,但不影响原始输出。

12

我正在编写一个小型预算脚本来关注我的财务状况。我想记录下所有交易及其发生时间的日志。

目前,我将支出作为参数输入:

f)
    echo "$OPTARG spent on food" | tee spendinglogs.log
    ... # take away money from monthly budget
    echo "$REMAINING_FOOD_BUDGET remaining" | tee spendinglogs.log

m)
    echo "$OPTARG spent on miscellaneous" | tee spendinglogs.log
    ... # take away money from monthly budget
    echo "$REMAINING_MISC_BUDGET remaining" | tee spendinglogs.log

... #etc

我不想将输出内容的时间戳显示在终端,但我希望在日志中记录输出的时间戳。有没有方法可以实现这个功能?

例如:

echo "$OPTARG spent on food" | tee `date %d-%m-%y %H_%M_%S` spendinglogs.log

但我无法想象那样做会起作用。

4个回答

19

编辑:已测试并更新了正确的信息

请查看来自moreutils软件包的ts

如果您正在使用bash,可以将其tee到shell管道作为文件:

echo "$OPTARG spent on food" | tee >(ts "%d-%m-%y %H_%M_%S" > spendinglogs.log)

我的上一个回答正确地陈述了上述正确的答案,但还使用了来自moreutils的不正确的答案peepee似乎在将stdin发送到输出管道之前缓冲它,因此这对于打时间戳不起作用(但对于时间不重要的命令则有效)。



ts是一个很好的工具。到目前为止,我只使用awk来进行时间戳记录。+1 - anishsane

2

试试这个:

echo something 2>&1 | while read line; do echo $line; echo "$(date) $line" >> something.log; done

0
以下代码片段将在日志文件的每一行前添加时间戳。 控制台输出没有任何时间戳。
exec &> >(tee -a >(sed "s/^/$(date) /" >> "${filename.log}"))

&> :同时将stdout和stderr重定向到文件

>> :将输出附加到文件末尾


0
function tee_with_timestamps () {
    local logfile=$1
    while read data; do
        echo "${data}" | sed -e "s/^/$(date '+%T') /" >> "${logfile}"
        echo "${data}"
    done
}

echo "test" | tee_with_timestamps "file.txt"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接