bash无限循环超过3个值

问题描述 投票:1回答:1

我有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做一些事情直到成功。

最好的方法是什么?

bash for-loop infinite-loop
1个回答
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.
© www.soinside.com 2019 - 2024. All rights reserved.