<分区>
在 Internet 上进行一些搜索后,Bash 似乎没有 do-while 循环。
这是正确的吗?是否有可靠的来源来证实这一点(缺乏证据表明存在 do-while 循环并不是说没有,也许只是一种说法不受欢迎)?
是否可以自己定义指令并实现 do-while 循环?有一种算法方法可以将 do-while 循环转换为 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/