linux - Linux Bash 有 do-while 循环吗?

标签 linux bash do-while

<分区>

在 Internet 上进行一些搜索后,Bash 似乎没有 do-while 循环。

这是正确的吗?是否有可靠的来源来证实这一点(缺乏证据表明存在 do-while 循环并不是说没有,也许只是一种说法不受欢迎)?

是否可以自己定义指令并实现 do-while 循环?有一种算法方法可以将 do-while 循环转换为 while 循环,但这不是这个问题的范围。

最佳答案

bash(或一般的 Posix shell)没有用于后测试循环(通常称为“do-while”循环)的显式语法,因为该语法是多余的。 while 复合语句允许您使用相同的语法编写前测试、后测试或中测试循环。

这是 shell while 循环的语义,来自 Posix :

The format of the while loop is as follows:

while compound-list-1
do
  compound-list-2
done

The compound-list-1 shall be executed, and if it has a non-zero exit status, the while command shall complete. Otherwise, the compound-list-2 shall be executed, and the process shall repeat.

“复合列表”是一系列命令;复合列表的退出状态是列表中最后一个命令的退出状态。

这意味着您可以将 while 循环视为如下编写:

while
  optional-pre-test-compound-list
  condition
do
  post-test-compound-list
done

也就是说,不要求要测试的条件紧跟在while关键字之后。所以相当于 C 语法:

do statements while (test);

while statements; test do :; done

do和done之间的:是必须的,因为shell语法不允许空语句。由于 : 不是元字符,因此它前后必须有空格或元字符;否则,它将被解析为前面或后面的标记的一部分。由于它被解析为命令,因此它后面还需要一个分号或换行符;否则 done 被视为 : 的参数。

关于linux - Linux Bash 有 do-while 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27761297/

相关文章:

Java,do while循环运行两次,然后再次请求输入

java - 为什么我的密码 do-while 循环在 Java 中不起作用?我做错了什么?

linux - Visual Studio 2010/3 的 Bash 脚本插件?

linux - awk 列减去一个常量

linux -/dev/mapper/fedora-root 满到96%,但是好像隐藏了超过50%的权重

java - 创建可执行的 bash 脚本,而无需用户调用 chmod 命令

java - 如何从 Java 运行 Mac OS 终端命令(使用运行时?)

bash -\( 在 bash 脚本中是什么意思

c - 为什么不执行 if 条件?

node.js - 当我 ssh 进入实例时, Node 版本与手动执行时不同