Skip to content

Instantly share code, notes, and snippets.

@tknerr
Last active April 11, 2018 20:41
Show Gist options
  • Save tknerr/cf058114770e67521896f467e35171aa to your computer and use it in GitHub Desktop.
Save tknerr/cf058114770e67521896f467e35171aa to your computer and use it in GitHub Desktop.
ping exercise in plain bash
$ ./pinger.sh "google.com facebook.com zuehlke.com"
average ping time for zuehlke.com: 63.600 ms
average ping time for facebook.com: 61.161 ms
average ping time for google.com: 61.953 ms
#!/bin/bash
function ping_time() {
ping -c1 $1 | grep 'time=' | cut -d ' ' -f 7 | cut -d '=' -f 2
}
function calc() {
bc <<< "scale=3;$1 $2 $3"
}
function avg_ping_time() {
local total=0
local num_pings=6
for i in $(seq 1 $num_pings); do
latency=$(ping_time $1)
total=$(calc $total '+' $latency)
sleep 10
done
echo "average ping time for $1: $(calc $total '/' $num_pings) ms"
}
HOSTS=${1:-localhost}
# spawn background processes for each host (so they run in parallel) and wait
for host in $HOSTS; do
avg_ping_time $host &
done
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment