Bash + Ping: Output with Timestamp

categories Computer    

One of the many things bash is so great to work with, is the flexibility to combinate the hardened tools at hand to create your desired output.

For example, I wanted to ping a host frequently (lets say every two minutes), and just add a readable timestamp to the output. Usually I’d use a network monitoring tool like Nagios for this task, but in this case it was just to discover when a host comes back alive and pop it onto my screen.

After a few minutes of putting pieces of bash commands together, I solved it this way:

ping -i 120 www.google.com | while read x; do echo "$(date +%T) $x"; done


08:10:24 PING www.google.com ( 56(84) bytes of data.
05:10:24 64 bytes from icmp_seq=1 ttl=57 time=9.82 ms
05:12:24 64 bytes from icmp_seq=2 ttl=57 time=9.25 ms
05:14:24 64 bytes from icmp_seq=3 ttl=57 time=24.4 ms
05:16:24 64 bytes from icmp_seq=4 ttl=57 time=9.81 ms
05:18:24 64 bytes from icmp_seq=5 ttl=57 time=60.4 ms

Mission accomplished!