Error code returned by utility ping
may vary depending on the occurrence:
Success: 0
Timed-out: 1
Unreachable Host: 2
So, it follows example (tested) of a script capable of solving your problem:
#!/bin/bash
IP_LIST=( 0.0.0.0
255.255.255.255
xxx.xxx.xxx.xxx
127.0.0.1
172.217.29.46
191.239.213.197
17.172.224.47
198.175.116.54 )
for ((i = 0; i < ${#IP_LIST[@]}; i++)); do
ping -q -c1 "${IP_LIST[i]}" &>/dev/null
case "$?" in
'0') STATUS="OK" ;;
'1') STATUS="TIMEOUT" ;;
'2') STATUS="INALCANCAVEL" ;;
*) STATUS="ERRO" ;;
esac
echo "IP: ${IP_LIST[i]} [${STATUS}]"
done
Exit:
IP: 0.0.0.0 [OK]
IP: 255.255.255.255 [INALCANCAVEL]
IP: xxx.xxx.xxx.xxx [INALCANCAVEL]
IP: 127.0.0.1 [OK]
IP: 172.217.29.46 [TIMEOUT]
IP: 191.239.213.197 [TIMEOUT]
IP: 17.172.224.47 [TIMEOUT]
IP: 198.175.116.54 [TIMEOUT]
A more reliable and robust method to solve your problem would be through the availability rate of each list IP.
The following is an example capable of calculating the availability rate of Ips in a list:
#!/bin/bash
IP_LIST=( 8.8.8.8
127.0.0.1
10.1.1.19
172.217.29.46
191.239.213.197
17.172.224.47
198.175.116.54 )
for ((i = 0; i < ${#IP_LIST[@]}; i++)); do
PCKT_LOSS=$(ping -q -c5 "${IP_LIST[i]}" | grep -oP '\d+(?=% packet loss)')
echo "IP: ${IP_LIST[i]} [Disponibilidade: $[100 - ${PCKT_LOSS}]%]"
done
Exit:
IP: 8.8.8.8 [Disponibilidade: 0%]
IP: 127.0.0.1 [Disponibilidade: 100%]
IP: 10.1.1.19 [Disponibilidade: 100%]
IP: 172.217.29.46 [Disponibilidade: 0%]
IP: 191.239.213.197 [Disponibilidade: 0%]
IP: 17.172.224.47 [Disponibilidade: 0%]
IP: 198.175.116.54 [Disponibilidade: 0%]
I hope I’ve helped!
The
for
is iterating over the number of script arguments$#
, would not be${#parameters[@]}
to iterate on thearray
? I think theeval...
is not necessary.– stderr
In this case, it makes no difference whether we are iterating over the parameters or over the array. But, even making this change, the error persists.
– Lucas Schneider
The script here worked, that IP for example is not valid and even then returns "ok"?
– stderr
any Ip, type 8.8.8.asdf
– Lucas Schneider
The error code may vary depending on the result of
ping
: Success: 0; No Response: 1; Other Errors: 2.– Lacobus