在 Bash 中模拟 Do-While 循环
Nilesh Katuwal 2023年1月30日 Bash Bash do-while
循环是编程中的一个基本思想,在多任务任务中非常有用。我们可以使用诸如 for、while 和 until 之类的许多函数来循环 bash 脚本。
在本课中,我们将介绍如何在 bash 中使用 do-while 循环。
Bash 中 do-while 循环的基本语法
do-while 循环的基本语法如下。
while [condition] do first command; second command; . . . nth command; done while 循环的参数可以是任何布尔表达式。当条件永远不会计算为 false 时,循环将变为无限。
点击 CTRL + C 停止无限循环。让我们看一个例子:
#!/bin/bash x=0 while [ $x -le 4 ] do echo "The value is $x" ((x++)) done 在示例中的每次迭代中,将打印变量的当前值并将其增加一。 $x 变量的初始值为 0。
上面的脚本将一直运行到第四行。后缀 -le 表示小于或等于。
输出:
The value is 0 The value is 1 The value is 2 The value is 3 The value is 4 Bash 中的 break 语句
我们在循环中使用 break 语句来在满足条件时终止循环。
例如,循环将在第九次迭代后在下面的脚本中终止。然而,我们可以通过使用 break 和 if 语句在第四次迭代中停止循环。
#!/bin/bash x=0 while [ $x -le 9 ] do echo "The value is $x" ((x++)) if [[ "$x" == '4' ]]; then break fi done 输出:
The value is 0 The value is 1 The value is 2 The value is 3 Bash 中的 continue 语句
continue 语句退出当前循环迭代并将程序控制转移到下一个迭代。
让我们看一个例子。当当前迭代项等于 3 时,continue 语句使执行返回到循环的开头并继续下一次迭代。
#!/bin/bash x=0 while [ $x -le 5 ] do ((x++)) if [[ "$x" == '3' ]]; then continue fi echo "The value is $x" done 输出:
The value is 1 The value is 2 The value is 4 The value is 5 The value is 6 正如上述输出中所预期的那样,当 $x 等于 3 时,它会跳过迭代并继续进行下一个迭代。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe