How to check if ip latency is greater than 0?

Asked

Viewed 289 times

-2

Code:

 if [ 'ping $1 -c1 |grep rtt |awk {'print$4'} |awk -F "/" {'print$2'}' -gt 0 ]
    then
    echo "OK"
 else
    echo "NO OK"
 fi

Error:

./latencia.sh: line 1: [: ping $1 -C1 |grep rtt |awk {print} |awk -F "/" {print}: expected integer expression NO OK

  • If I understand your command, you are determining the average time of ping for a particular machine. (1) is not expected to be less than or equal to zero... (2) -gt makes comparison between integers (3) the quotation around the big comandi is exchanged.

2 answers

0

To get the values, you can use the command:

ping $1 -c1 | cut -sd '/' -f5

But you still can’t compare a float to an integer, other than the problems that other users cited.

If you really want to compare the value to zero, you can do it this way:

# Salva o valor de retorno na váriavel $avg
avg=$(ping $1 -c1 | cut -sd '/' -f5)
# Converte a variável $avg para int e compara com zero
if [ ${avg%.*} -gt 0 ]; then
    # retorna OK caso seja maior que zero
    echo "OK"
else
    # retorna NO OK caso seja igual ou menor que zero
    echo "NO OK"
fi

0

You can compare two float numbers in bash using the command bc:

avg_rtt=$(ping $1 -c1 |grep rtt |awk {'print$4'} |awk -F "/" {'print$2'})

if (( $(echo "$avg_rtt > 0" |bc -l) )); then  
   echo "OK"
else
   echo "NO OK"
fi

Still, you’re comparing it to 0 (and here you can replace it with any float), which is never expected in a round-trip time(rtt) medium in one ping.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.