Target:
- Generate a list of timestamp/RTT values, one per second, into a text file suitable for later processing and graphing
Limitations:
- Utilize base system; don't require extra packages
- Operate in 'streaming' mode: don't use bourne shell 'while' loop and keep fork()ing to a minimum
Result:
ping -n 172.16.44.18 | sed -le 's/^.* \(time=[0-9.]*\) ms$/\1/; /^time=/!d; s/^time=//g; /\./!s/$/./g; /\.[0-9][0-9][0-9]$/!s/$/0/g; /\.[0-9][0-9][0-9]$/!s/$/0/g; /\.[0-9][0-9][0-9]$/!s/$/0/g; s/\.//g' | awk '{ printf; printf "\t"; system("date +%s"); close("date +%s"); fflush() }'
Breakdown:
s/^.* \(time=[0-9.]*\) ms$/\1/; # Trim out all but the RTT
/^time=/!d; # Eliminate all other lines
s/^time=//g; # Remove the 'time=' tag; want only the number
/\./!s/$/./g; # Add a decimal point onto the end if it doesn't exist
/\.[0-9][0-9][0-9]$/!s/$/0/g; # Add a 0 to the end if there are fewer than three digits after the decimal point
/\.[0-9][0-9][0-9]$/!s/$/0/g; # Add a second 0
/\.[0-9][0-9][0-9]$/!s/$/0/g; # Add a third 0; now the number should be normalized to microseconds
s/\.//g; # Remove the decimal point, leaving only an integer number of microseconds
{ printf; # Print out the RTT
printf "\t"; # Print a tab
system("date +%s"); # Print the current seconds-since-epoch
close("date +%s"); # A kludge, but there's no other way to acquire the date without using gawk or calling 'date' somehow
fflush(); # Line-buffer the output
}
Final Script:
#!/bin/sh
host="${1:-172.16.44.18}"
if ! ping -o -c1 -t1 -W1 "${host}" >/dev/null 2>&1
then
echo "host ${host} must respond to ICMP echo requests" >&2
exit 1
fi
ping -n "${host}" | sed -le 's/^.* time=\([0-9.]*\) ms$/time=\1/; /^time=/!d; s/^time=//g; /\./!s/$/./g; /\.[0-9][0-9][0-9]$/!s/$/0/g; /\.[0-9][0-9][0-9]$/!s/$/0/g; /\.[0-9][0-9][0-9]$/!s/$/0/g; s/\.//g' | awk '{ printf; printf " "; system("date +%s"); close("date +%s"); fflush() }'