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:


    would become

    [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?

  • moreutils includes ts which does this quite nicely:

    command | ts '[%Y-%m-%d %H:%M:%S]'

    It eliminates the need for a loop too, every line of output will have a timestamp put on it.

    $ echo -e "foo\nbar\nbaz" | ts '[%Y-%m-%d %H:%M:%S]'
    [2011-12-13 22:07:03] foo
    [2011-12-13 22:07:03] bar
    [2011-12-13 22:07:03] baz

    You want to know when that server came back up you restarted? Just run ping | ts , problem solved :D.

    How have I not known about this?!?!?! This complements tail -f amazingly! `tail -f /tmp/script.results.txt | ts`

    What about in cygwin? Is there something similar? It doesn't appear Joey's moreutils are there.

    if I don't have ts command, what should I use?

    If it's not working, try redirecting stderr to stdout e.g. `ssh -v 2>&1 | ts`

    Note that if you want fractional seconds, use "%.S". See `man ts`.

    Install by doing `sudo apt install moreutils` on Debian and `yum install moreutils` on Fedora.

    It's written in perl, so it should be portable

    I think pointing out the parameter `-s` is useful. As that displays the runtime of the command. I personally like using both `ts` and `ts -s` at the same time. Looks something like this: `command | ts -s '(%H:%M:%.S)]' | ts '[%Y-%m-%d %H:%M:%S'`. This prepends the log lines like this: `[2018-12-04 08:31:00 (00:26:28.267126)] Hai <3`

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM