Sorting IP Addresses in BASH
I was working on a little script to test if a bunch of hosts is reachable by ping.
The first version of the script was ready in a minute, but sending pings to hundred hosts in sequence takes some time. Especially if the hosts are down the ping takes a full second until timeout.
To call the pings in parallel is just wrapping the ping command in a
( ... ) &. But this will change the order of the output and the parent script ends before the child scripts do.
To get back the synchronization and having the output sorted I piped the whole output to sort.
As sort uses the alphabetical order to sort the IP Addresses the order is not as expected. But sort has a flag
-V to sort versions – which are technically the same as IP addresses: dot separated numbers.
Here comes the example:
for i in $(seq 1 10); do ( ip=$(printf "10.0.0.%s" "$i") if ping -W 1 -c 1 $ip > /dev/null; then printf "%s e[32m%se[0m " "$ip" "up" else printf "%s e[31m%se[0m " "$ip" "down" fi ) & done | sort -V
Btw.: The watch command supports a
--color flag which allows to run the script in a loop.