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

标签 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 中实现类似上面的东西吗?

一如既往,提前感谢您。

最佳答案

您需要两个嵌套循环:一个外部无限循环和一个从输入文件中读取每一行的内部循环。 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

关于linux - 在无限循环中逐行读取文件直到中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50052401/

相关文章:

bash - 如何使用 checkinstall 管理多个包依赖?

linux - 将逗号分隔的数字模式匹配为字符串

linux - 在 bash 脚本的大括号中运行命令时的不同结果

linux - 递归查找所有不以注释开头的php文件

regex - 如何以不区分大小写的方式将文件复制到 HDFS

linux - 测试 nginx 和 alpine 与 hello world 的连接

c# - 如何在 C# 中从 IFileDialogCustomize GetEditBoxText() 获取字符串

bash - 将文件表(存储为 bytea)复制到磁盘上的单个文件中?

linux - ant 的 <exec> 中的引号问题

linux - Path::new(many-subdirs) 对于 Linux 和 Windows 是否足够好?