Skip to content
Advertisement

reading file line by line in an infinite loop until break

I’m trying to implement an infinite loop bash script for reading in a file, doing something and check counter condition, when counter condition reaches 0 it breaks out of the infinite loop. I’ve tried several iteration and none has worked for me. Pseudo-code would be something line this..

#!/bin/bash
counter=10
while true
do
  read host from file
  ping -c 1 host > /dev/null
  if [ $? -eq 0 ]
  then
    (($counter+1))
    do_something_to_the_host
  else
    (($counter-1))
    if [ $counter -eq 0 ]
    then
      break # this breaks out of the while true infinite loop
    fi
  fi
done

Can anyone show me how to implement something like the above in bash please?

As always, thanking you in advance.

Advertisement

Answer

You want two nested loops: an outer infinite loop, and an inner loop that reads each line from the input file. break takes a numerical argument to specify how many loops to break out of.

counter=10
while true
do
  while read host
  do
    ping -c 1 host > /dev/null
    if [ $? -eq 0 ]
    then
      (($counter+=1))
      do_something_to_the_host
    else
      (($counter-=1))
      if [ $counter -eq 0 ]
      then
        break 2
      fi
    fi
  done < file
done
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement