Ping reboot script percentage packet loss

need script for reboot modem when packet loss > 70 i see it:

    a="$(ping -c10 "host" | awk 'END{print}' | awk '{ print $7 }' | sed s/%//g)"; 
if [ "$a" -gt "$b" ]; then
        echo "trouble ping" #reboot modem
        echo "ping ok"

When the host does not answer first str = 100 (without "%") its correct, but when he answers the output is empty (why not 0), i can't understand the reason


  • ping output on my system when there's 0% packet loss and 100% packet loss:

    $ ping -c10
    PING ( 56 data bytes
    64 bytes from icmp_seq=0 ttl=53 time=75.890 ms
    ... snip ...
    64 bytes from icmp_seq=9 ttl=53 time=75.553 ms
    --- ping statistics ---
    10 packets transmitted, 10 packets received, 0% packet loss
    round-trip min/avg/max/stddev = 73.983/76.589/78.678/1.682 ms
    $ ping -c10
    PING ( 56 data bytes
    --- ping statistics ---
    10 packets transmitted, 0 packets received, 100% packet loss

    It may make more sense to search for the string packet loss and then take the 7th (white space delimited) field, eg:

    ping -c10 "host" | awk '/packet loss/{print int($7+0)}'

    When applied to the 2x scenarios above this generates 0 and 100, respectively.


    • in the awk code the $7+0 has the effect of stripping off trailing non-numeric characters (eg, %)
    • in the awk code the int() insures we only generate an integer (in case ping were to ever generate a float/real value); bash only works with integers so we need to make sure we only pass an integer back to the calling process
    • OP may want additional logic to handle a ping command that goes walkabout, eg, generates an error (ping: unknown host), generates nothing, hangs, etc