Speed up the loop in shell script

Hi

I have written a shell script which will test 300 to 500 IPs to find which are pinging and which are not pinging.

the script which give output as

10.x.x.x is pining
 10.x.x.x. is not pining
 -
 -
 -
 10.x.x.x is pining 

like above.

But, this script is taking more time to display the output, as it is checking ONe by One IP.

My script is as below

 !/bin/bash
 while read line 
 do
 ping -c 1 $line &> /dev/null
 if [ $? -eq 0 ]; then
     echo "$line is pinging"
 else
     echo "$line is not pining"
 done < IP_list
 

can any one please guide me to speed up my script to provide speed output. as the loop above should run on 300 to 500 Ips.

the script is taking more than 30 mins to complete the execution.

Hello kumar85shiv,

Could you please try following and let me know if this helps, though I haven't tested it with 500 or 300 IPs, I only tested with 5 IPs and I am getting results within a second, please try and let me know on same, also not sure how your script worked without closing if condition properly as I saw fi is missing in the post shown.

while read line 
do
if [[ -n  $(ping -c1 $line 2>/dev/null) ]] 
then
    echo "$line is pinging"
else
    echo "$line is not pinging"
fi
done < "Input_file"

EDIT: Also adding one more way to make script shorter and you could try with this if this script is helpful to you and taking less time.

while read ip; do
    ping -c1 "$ip" &>/dev/null && echo $ip success || echo $ip fail
done < "Input_file"
 

Thanks,
R. Singh

Try

( for i in 10.1.1.{1..254} ; do ( ping -n -c 1 -w 1 $i &>/dev/null && printf "%-16s %s\n" $i responded ) & done ; wait )
10.1.1.1         responded
10.1.1.xx        responded
10.1.1.xx        responded

hi, you can launch n ping in parallel, example with 10 ping in // :

#!/bin/bash
cnt=0;
while read line 
do
  [ $((cnt++)) -eq 10 ] && cnt=0 && wait
  {
  ping -c 1 $line &> /dev/null
  if [ $? -eq 0 ]; then  
     echo "$line is pinging"  
  else
      echo "$line is not pining"
  fi
  } &
done < IP_list
wait

regards.

Hi Disedorgue,

i tried your code, but giving the below error

 ./ping_fast.sh: line 12: syntax error near unexpected token `}'
./ping_fast.sh: line 12: `   }& '

Install fping!

fping < IP_list

I corrected post: I just forget to close if condition with token "fi" :o