Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add timestamp to tee'd output, but not original output

Tags:

bash

tee

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.

like image 495
Brydon Gibson Avatar asked Aug 31 '16 01:08

Brydon Gibson


People also ask

How do you use a tee?

The tee command, used with a pipe, reads standard input, then writes the output of a program to standard output and simultaneously copies it into the specified file or files. Use the tee command to view your output immediately and at the same time, store it for future use.


2 Answers

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).

like image 157
iobender Avatar answered Oct 20 '22 17:10

iobender


Try this:

echo something 2>&1 | while read line; do echo $line; echo "$(date) $line" >> something.log; done
like image 1
Andrew Ivanov Avatar answered Oct 20 '22 17:10

Andrew Ivanov