Add timestamp to tee'd output, but not original output
Asked Answered
O

4

15

I'm writing a little budget script to keep an eye on my finances. I'd like to keep a log of all of my transactions and when they happened.

Currently, I input spendings as an argument:

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

I don't want to timestamp output to the terminal, but I do want to timestamp output to the logs. Is there a way to do this?

For example

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

But I can't imagine that working.

Overlay answered 31/8, 2016 at 1:26 Comment(0)
U
22

EDIT: Tested and updated with correct info

Check out ts from the moreutils package.

If you're using bash, you can tee to a shell pipe as a file:

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

My previous answer correctly stated the above, correct answer, but also an incorrect one using pee, also from moreutils. pee appears to buffer stdin before sending it to the output pipes, so this will not work with timestamping (it will work with commands where the timing is not important however).

Undine answered 31/8, 2016 at 1:33 Comment(2)
ts is a good utility. So far, I was only using awk for time-stamping. +1Cassimere
The fact that pee was buffering stdin was a bug, fixed in moreutils 0.62 on 2017-12-31 (in the changelog: "pee: Don't buffer input, bringing behavior into line with tee."). I don't see any issue with pee from moreutils 0.69, tested with { echo a; sleep 2; echo b; } | pee cat "ts %T > /dev/tty".Menarche
W
3

Try this:

echo something 2>&1 | while read line; do echo $line; echo "$(date) $line" >> something.log; done
Wethington answered 2/2, 2021 at 11:56 Comment(0)
M
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"
Morale answered 20/11, 2022 at 13:27 Comment(0)
E
-1

The below snippet is prepending timestamp in front of each line in the log file. The console output is without any timestamp.

exec &> >(tee -a >(sed "s/^/$(date) /" >> "${filename.log}"))

&> : for both stdout and stderr

>> : for appending in a file

Expedition answered 6/12, 2022 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.