1

There are many duplicate questions/examples on doing a comparison of variables in BASH, but none seem to work for me.

Code logic: Derive the (average) value of ping_val by executing a command:

ping_val=`ping -c 4 8.8.8.8| tail -1| awk '{print $4}' | cut -d '/' -f 2`

Then, if the value is less than 20, decrement another variable by 20:

if [ $ping_val -lt 20 ] #line 30
then
  $tot_health = $tot_health - 20
fi

Here is my output: ./my-report.sh: line 30: [: 65.464: integer expression expected

Note: The value of ping_val has been verified because I through the raw number up later in a chart.

wiwinut
  • 75
  • 1
  • 7
  • You could do this with one `awk` call: `tot_health=$(ping -c 4 8.8.8.8 | awk -F'[ /]' -v t="$tot_health" 'END{ print ($8<=20 ? t-20 : t) }')` – Freddy Mar 09 '20 at 19:38

2 Answers2

0

There are many errors in your original script. Basically your syntax was your problem.

Here you have a working version.

ping_val=$( ping -c 4 8.8.8.8 | tail -1 | awk '{print $4}' | cut -d '/' -f 2 )

if [[ awk -v PING_VAL="$ping_val" 'BEGIN{ if(PING_VAL <20) { exit(0)} else{ exit(1)}}' ]] 
then
  tot_health=$(( tot_health - 20 ))
fi

Hope it helps!

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49
0

The last line of ping looks like this:

rtt min/avg/max/mdev = 36.731/72.502/90.776/21.038 ms

You are parsing out what is 72.502 in this example. This is not an integer. Bash only works on integers. If you want to compare floating point numbers, you need an external tool like bc. You could also use your favorite command line language (awk, python, perl, etc). Since you want to compare to an integer anyway (specifically with a less than compare), you can just truncate off the decimal and compare.

Something like this will get your comparison working:

if [ ${ping_val/.*} -lt 20 ] #line 30
then
  tot_health=$((tot_health - 20))
fi

All ${ping_val} is doing, is taking 72.502 and making it 72. This should never change the logic of your program because you are doing a less than comparison.

Jason
  • 2,493
  • 2
  • 27
  • 27
  • Hi Jason. That worked! I had a feeling ti had something to do with the floating point result. Thanks so much! – wiwinut Mar 09 '20 at 19:28