如何在 Bash 中跳出循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18488651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to break out of a loop in Bash?
提问by lulyon
I want to write a Bash script to process text, which might require a while loop.
我想编写一个 Bash 脚本来处理文本,这可能需要一个 while 循环。
For example, a while loop in C:
例如,C 中的 while 循环:
int done = 0;
while(1) {
...
if(done) break;
}
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:
我想编写一个与此等效的 Bash 脚本。但是我通常使用的以及我读过的所有经典示例都显示了以下内容:
while read something;
do
...
done
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.
它没有提供有关如何执行while(1){}
and 的帮助break;
,它在 C 中定义明确并广泛使用,而且我不必为 stdin 读取数据。
Could anyone help me with a Bash equivalent of the above C code?
任何人都可以帮助我使用与上述 C 代码等效的 Bash 吗?
回答by chepner
It's not that different in bash
.
在bash
.
done=0
while : ; do
...
if [ "$done" -ne 0 ]; then
break
fi
done
:
is the no-op command; its exit status is always 0, so the loop runs until done
is given a non-zero value.
:
是无操作命令;它的退出状态始终为 0,因此循环会一直运行,直到done
被赋予一个非零值。
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.
您可以通过多种方式设置和测试 的值done
以退出循环;我上面展示的那个应该可以在任何 POSIX 兼容的 shell 中工作。
回答by lurker
while true ; do
...
if [ something ]; then
break
fi
done