如何突破Bash的循环? [英] How to break out of a loop in Bash?

查看:78
本文介绍了如何突破Bash的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个Bash脚本来处理文本,这可能需要while循环.

I want to write a Bash script to process text, which might require a while loop.

例如,在C中进行while循环:

For example, a while loop in C:

int done = 0;
while(1) {
  ...
  if(done) break;
}

我想编写一个与之等效的Bash脚本.但是我通常使用的,以及我阅读的所有经典示例都显示的是:

I want to write a Bash script equivalent to that. But what I usually used and as all the classic examples I read have showed, is this:

while read something;
do
...
done

它对如何做while(1){}break;没有任何帮助,这在C语言中定义清楚并广泛使用,并且我不必读取stdin的数据.

It offers no help about how to do while(1){} and break;, which is well defined and widely used in C, and I do not have to read data for stdin.

有人可以用上述C代码的Bash等效项帮助我吗?

Could anyone help me with a Bash equivalent of the above C code?

推荐答案

bash没什么不同.

done=0
while : ; do
  ...
  if [ "$done" -ne 0 ]; then
      break
  fi
done

:是无操作命令;它的退出状态始终为0,因此循环将一直运行,直到done被赋予非零值为止.

: is the no-op command; its exit status is always 0, so the loop runs until done is given a non-zero value.

有很多方法可以设置和测试done的值以退出循环.我上面显示的代码应该可以在任何POSIX兼容的shell中使用.

There are many ways you could set and test the value of done in order to exit the loop; the one I show above should work in any POSIX-compatible shell.

这篇关于如何突破Bash的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆