Prepending a timestamp to each line of output from a command
I wish to prepend a timestamp to each line of output from a command. For example:
[2011-12-13 12:20:38] foo
[2011-12-13 12:21:32] bar
[2011-12-13 12:22:20] baz
…where the time being prefixed is the time at which the line was printed. How can I achieve this?
Firstly, if you are expecting these timestamps to actually represent an event, bear in mind that since many programs perform line buffering (some more aggressively than others), it is important to think of this as close to the time that the original line would have been printed rather than a timestamp of an action taking place.
You may also want to check that your command doesn’t already have an inbuilt feature dedicated to doing this. As an example,
ping -D exists in some
ping versions, and prints the time since the Unix epoch before each line. If your command does not contain its own method, however, there are a few methods and tools that can be employed, amongst others:
Bear in mind that since many shells store their strings internally as cstrings, if the input contains the null character (