Shell脚本:嵌套循环和continue

5
while [condition]
do
  for [condition]
  do
    if [ "$x" > 3 ];then
      break
    fi
  done

  if [ "$x" > 3 ];then
    continue
  fi
done

在上面的脚本中,我必须两次测试"$x" > 3。实际上,第一次测试时,如果为真,我想跳出while循环并继续下一个while循环。
有没有更简单的方法,可以使用类似continue 2的语句来跳出外层循环?

2
为什么不在内部循环中使用 continue 2 - P.P
1
是的,continue n。你确定 for [condition]...通常是for n in a b c或类似的形式。祝好运。 - shellter
1个回答

1
“break”和“continue”是“goto”的近亲,通常应避免使用,因为它们引入了一些无名条件,导致程序控制流的跳跃。如果存在需要跳转到程序的其他部分的条件,则下一个阅读代码的人会感谢您为该条件命名,这样他们就不必自己去理解!
在您的情况下,您的脚本可以更简洁地编写为:
dataInRange=1
while [condition -a $dataInRange]
do
  for [condition -a $dataInRange]
  do
    if [ "$x" > 3 ];then
      dataInRange=0
    fi
  done
done

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接