Linux Bash是否有do-while循环?

前端之家收集整理的这篇文章主要介绍了Linux Bash是否有do-while循环?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Emulating a do-while loop in Bash3个
在互联网上进行一些搜索之后,看起来Bash没有do-while循环.

它是否正确?有没有可靠的来源来证实这一点(缺乏证据表明有一个do-while循环不是没有一个的论证,也许一个陈述只是不受欢迎)?

是否可以自己定义指令,从而实现do-while循环?有一种算法可以在while循环中转换do-while-loop,但这不是这个问题的范围.

解决方法

bash(或一般的Posix shell)没有明确的后测试循环语法(通常称为“do-while”循环),因为语法是多余的. while复合语句允许您编写预测试,后测试或中间测试循环,所有这些都使用相同的语法.

这是从Posix开始的shell while循环的语义:

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语法不允许空语句.因为:不是元字符,它必须在它之前和之后有空格或元字符;否则,它将被解析为前一个或后一个令牌的一部分.因为它被解析为一个命令,所以它后面还需要一个分号或换行符;否则将完成视为:.

原文链接:https://www.f2er.com/linux/394713.html

猜你在找的Linux相关文章