在3个值上进行bash无限循环

时间:2019-03-26 04:18:00

标签: bash for-loop infinite-loop

我有3个静态值:aabbcc。我想用退出情况无限期地遍历它们。 编写简单的循环很容易:

for i in aa bb cc; do 
   echo $i
done

但是我想无限循环,直到出现某种情况:

for i in aa bb cc; do 
   echo $i
   if [ somecondition ]; then
      doSomething
      break
   fi
done

somecondition取决于外部条件和i。看起来应该尝试使用i进行操作,直到成功为止。

最好的方法是什么?

1 个答案:

答案 0 :(得分:2)

一种简单的方法是将代码嵌套在无限循环内:

while true; do
    for i in aa bb cc; do
        echo $i;
        if [ somecondition ]; then
            doSomething
            break 2
        fi
    done
done

请注意,break命令现在具有参数2

man bash说:

    break [n]
        Exit from within a for, while, until, or  select
        loop.   If  n  is  specified, break n levels.  n
        must be >= 1.  If n is greater than  the  number
        of  enclosing  loops,  all  enclosing  loops are
        exited.  The return value is 0 unless n  is  not
        greater than or equal to 1.