Ping with timestamp on Mac OS X

From ShawnReevesWiki
Jump to navigationJump to search

Adding a timestamp to ping's output

Here's a command to save a record of ten thousand pings with a timestamp. This code, to be run in a BASH terminal command line, combines the methods, found in the references below, of adding a timestamp and saving the output to a file:

ping -i 2 -c 10000 google.com | while read pong; do echo "$(date -j '+%Y-%m-%d %H:%M:%S') $pong" 1>>~/PingsWithDate.txt;done
Explanation of commands in the above code
ping google.com
Send a periodic message to google.com asking for a simple reply. The result is the number of each ping in series (icmp_seq), the maximum amount of IP routers allowed to transmit the message, and the time taken by the round-trip.
-i 2
Wait 2 seconds between pings.
-c 10000
Repeat the ping ten thousand times.
|
"Pipe" the output to the following command.
while read pong; do
If there is any output from the pipe, set the variable pong to the output and do the following commands up to "done", returning here to check for more output. Go to the command after "done" if there is no more output.
echo ""
Copy the following to the standard output.
$(date -j '+%Y-%m-%d %H:%M:%S')
Print the current date, without trying to set it (-j), in the format of year-month-date hour:minute:second.
$pong
Also print the output from the ping command stored in the variable pong.
1>>~/PingsWithDate.txt
Redirect the output of echo from standard output to the end of the file PingsWithDate.txt in the user folder. If the file doesn't yet exist, a new file will be made, else the results will be appended to the file without overwriting the existing contents.
Typical output
2016-05-16 12:26:28 PING google.com (172.217.4.46): 56 data bytes
2016-05-16 12:26:28 64 bytes from 172.217.4.46: icmp_seq=0 ttl=55 time=17.574 ms
2016-05-16 12:26:30 64 bytes from 172.217.4.46: icmp_seq=1 ttl=55 time=18.960 ms
2016-05-16 12:26:32 64 bytes from 172.217.4.46: icmp_seq=2 ttl=55 time=19.141 ms
2016-05-16 12:26:34 64 bytes from 172.217.4.46: icmp_seq=3 ttl=55 time=18.279 ms
2016-05-16 12:26:36 64 bytes from 172.217.4.46: icmp_seq=4 ttl=55 time=20.297 ms

References

Advanced bash scripting guide
http://tldp.org/LDP/abs/html/io-redirection.html
Add timestamp to Ping
http://tech.jocke.no/2010/09/27/add-timestamp-to-ping/