I have a program (server) and I am looking for a way (script) that will redirect (or better duplicate) all its stdout
to file and add timestamp for each entry.
I've done some research and the furthest I could get was thanks to How to add timestamp to STDERR redirection. It redirects stdout
but the timestamp added is of the time when the script finishes:
#!/bin/bash ./server | ./predate.sh > log.txt
code of predate.sh
:
#!/bin/bash while read line ; do echo "$(date): ${line}" done
It seems that server output is flushed after exit of the program.(without redirecting it works fine). Also if I try using predate.sh
on given example in mentioned thread, it works perfectly. I am aware it would be easy adding a timestamp to the main program but I would rather avoid editing its code.
For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.
&>word (and >&word redirects both stdout and stderr to the result of the expansion of word. In the cases above that is the file 1 . 2>&1 redirects stderr (fd 2) to the current value of stdout (fd 1).
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
picocom
is piped to awk
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 in awk
tee
which diverts it to a file. (you can find some stuff about tee
here)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With