How to add timestamp while redirecting stdout to file in Bash?
I recently needed exactly that: receive log messages in a serial console (picocom), print them to a terminal and to a file AND prepend the date.
What I now use looks s.th. like this:
picocom -b 115200 /dev/tty.usbserial-1a122C | awk '{ print strftime("%s: "), $0; fflush(); }' | tee serial.txt
- the output of
picocom
is piped toawk
awk
prepends the date (the%s
option converts the time to the Number of seconds since 1970-01-01 00:00:00 UTC - or use%c
for a human-readable format)fflush()
flushes any buffered output inawk
- that is piped to
tee
which diverts it to a file. (you can find some stuff abouttee
here)
moreutils ts
Absolute date and time is the default:
$ sudo apt-get install moreutils$ (echo a;sleep 1;echo b;sleep 3;echo c;sleep 2;echo d;sleep 1) | ts | tee myfile$ cat myfileApr 13 03:10:44 aApr 13 03:10:45 bApr 13 03:10:48 cApr 13 03:10:50 d
or counting from program start with ts -s
:
$ (echo a; sleep 1; echo b; sleep 3; echo c; sleep 2; echo d; sleep 1) | ts -s00:00:00 a00:00:01 b00:00:04 c00:00:06 d
or deltas for benchmarking with ts -i
:
$ (echo a; sleep 1; echo b; sleep 3; echo c; sleep 2; echo d; sleep 1) | ts -i00:00:00 a00:00:01 b00:00:03 c00:00:02 d$ (echo a; sleep 1; echo b; sleep 3; echo c; sleep 2; echo d; sleep 1) | ts -i '%.s'0.000010 a0.983308 b3.001129 c2.001120 d
Tested on Ubuntu 18.04, moreutils 0.60.
For Me Your Code is working perfectly fine
Check this is what I tried
test.sh
#!/bin/bashwhile true; do echo "hello"done
predate.sh
#!/bin/bashwhile read line; do echo $(date) ":" $line; done
then
./test.sh | ./predate.sh
gives me
Tue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : helloTue Jan 14 17:49:47 IST 2014 : hello
This can be redirected to some file using ">" or ">>" for append