0

I am trying to find out which search engine will give the fastest ping for me and then get the result in a single output but I am not able to figure out how to put if statement for that in shell script. My code is below

png=10000    
for item in ${array[*]}
            do
                png_cal=`ping -c 4 "$item" | tail -1| awk '{print $4}' | cut -d '/' -f 2`
                if [[ $png < $png_cal ]];then
                    png=${png_cal}
                    link=${item}
                fi
            done

and my program is not going in the loop again after first loop.

tushar_ecmc
  • 186
  • 2
  • 21

1 Answers1

1

Your immediate problem is how to compare floating point numbers in Bash, whereas your code would only compare integers.

I got it to work like this:

array=(www.google.com www.facebook.com www.linkedin.com www.stackoverflow.com)
fastest_response=2147483647 # largest possible integer
for site in ${array[*]}
do
  this_response=`ping -c 4 "$site" | awk 'END { split($4,rt,"/") ; print rt[1] }'`
  if (( $(bc -l <<< "$this_response < $fastest_response") )) ; then
    fastest_response=$this_response
    fastest_site=$site
  fi
  echo "Got $this_response for $site ; fastest so far $fastest_site"
done
echo $fastest_site

Further explanation:

  • See this related Stack Overflow answer for why the expression to compare floats in Bash is so complicated.

  • I simplified the calls to tail, awk etc by just doing all that in awk, which is cleaner.

  • Notice I gave the variables more meaningful names. It's so much easier to think about code when the variable names announce themselves precisely for what they really are.

  • Instead of 10,000 I chose to use the largest possible integer in Bash. It's just a style thing as it seemed less arbitrary than 10,000.

  • I also made the script communicate a bit with the user, because the user won't want to sit there waiting for pings without knowing what's going on.

And the winner is:

$ bash test.sh                                                                                                                                                
Got 21.786 for www.google.com ; fastest so far www.google.com
Got 20.879 for www.facebook.com ; fastest so far www.facebook.com
Got 20.555 for www.linkedin.com ; fastest so far www.linkedin.com
Got 21.368 for www.stackoverflow.com ; fastest so far www.linkedin.com
www.linkedin.com
Alex Harvey
  • 14,494
  • 5
  • 61
  • 97