Add timestamps to every line

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-11-21

How to add timestamps to every line of output in bash, i.e. to commands that don't already include it?

Pipe the output to the ts command

brew install moreutils
command | ts
# ts optionally takes custom timestamp formats as needed

By default it gives absolute timestamps

ping 10.0.0.1 | ts

Nov 23 02:51:48 PING 10.0.0.1 (10.0.0.1): 56 data bytes
Nov 23 02:51:48 Request timeout for icmp_seq 0
Nov 23 02:51:49 Request timeout for icmp_seq 1
Nov 23 02:51:50 Request timeout for icmp_seq 2
√Nov 23 02:51:51 Request timeout for icmp_seq 3
Nov 23 02:51:52 Request timeout for icmp_seq 4

But the -s flag makes it incremental

ping 10.0.0.1 | ts -s
00:00:01 PING 10.0.0.1 (10.0.0.1): 56 data bytes
00:00:01 Request timeout for icmp_seq 0
00:00:02 Request timeout for icmp_seq 1
00:00:03 Request timeout for icmp_seq 2
00:00:04 Request timeout for icmp_seq 3

And you can pass it a format

ping 10.0.0.1 | ts %l":"%M%p
2:53AM PING 10.0.0.1 (10.0.0.1): 56 data bytes
2:53AM Request timeout for icmp_seq 0
2:53AM Request timeout for icmp_seq 1