How to prefix each output line of a programme with the time and date
Many programmes produce logs, e.g. apache produces log files of webpages that people visit. One common feature of these log files is that each line has the time and date that the event happened at. This is very convienent because you can easily search for things that happened on a certain date or at a certain time.
Sometimes you might want to run a command that will print some output, and it might take a while. In cases like this it would be helpful to have a timestamp on each line. This is a simple little snippet you can put onto the end of a big command that will print timestamps.
The magic here is the 'read' built in. It will read the whole line (and store it in the shell variable line). However if there is no output yet, it will just sit there and the contents of the loop (which prints out the timestamp) will not be run. Since the time is only evaluated inside the loop, it will not update the time until it has a line. i.e. it will calculate a timestamp when a line is output by the first programme.
This is all you need to add to your command to get some nice output
$ command | while read line ; do NOW=$(date -Iseconds) ; echo -e "${NOW}\t${line}" ; done
Hi, interest post. I'll write you later about few questions!
Comment by Kelly Brown — Jun 12, 2009 8:25:53 PM | # - re
with NOW=$(date) - ( just using a simpler date format) this did it for me - thanks!
Comment by Steven — Dec 23, 2009 9:36:20 PM | # - re