在无限循环中逐行读取文件直到中断

时间:2018-04-26 21:55:53

标签: linux bash shell

我试图实现一个无限循环bash脚本来读取文件,做某事并检查计数器条件,当计数器条件达到0时,它会突破无限循环。我已经尝试了几次迭代,没有一个对我有效。伪代码就是这个......

#!/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

有人能告诉我如何在bash中实现上述内容吗?

一如既往,提前感谢你。

1 个答案:

答案 0 :(得分:2)

您需要两个嵌套循环:一个外部无限循环,以及一个从输入文件中读取每一行的内部循环。 break使用数字参数来指定要突破的循环数。

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
相关问题