问题描述
我想编写一个 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 中定义明确并广泛使用,我没有为标准输入读取数据.
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
中并没有什么不同.
It's not that different in bash
.
workdone=0
while : ; do
...
if [ "$workdone" -ne 0 ]; then
break
fi
done
:
是无操作命令;它的退出状态始终为 0,因此循环运行直到 workdone
被赋予一个非零值.
:
is the no-op command; its exit status is always 0, so the loop runs until workdone
is given a non-zero value.
有很多方法可以设置和测试workdone
的值以退出循环;我上面展示的那个应该可以在任何兼容 POSIX 的 shell 中工作.
There are many ways you could set and test the value of workdone
in order to exit the loop; the one I show above should work in any POSIX-compatible shell.
这篇关于如何在 Bash 中跳出循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!