Unix / Linux - Shell 循环类型

在本章中,我们将讨论 Unix 中的 shell 循环。 循环是一种功能强大的编程工具,可让您重复执行一组命令。 在本章中,我们将研究以下可供 Shell 程序员使用的循环类型 −

您将根据情况使用不同的循环。 例如,while 循环执行给定的命令,直到给定的条件保持为真; until 循环执行直到给定条件变为真。

一旦您进行了良好的编程练习,您将获得专业知识,从而开始根据情况使用适当的循环。 此处,whilefor 循环可用于大多数其他编程语言,例如 CC++PERL 等。


嵌套循环

所有循环都支持嵌套概念,这意味着您可以将一个循环放在另一个相似或不同的循环中。 根据您的要求,此嵌套最多可以无限次。

下面是一个嵌套 while 循环的例子。 其他循环可以根据编程要求以类似的方式嵌套 −


嵌套 while 循环

可以将一个 while 循环用作另一个 while 循环主体的一部分。

语法

while command1 ; # this is loop1, the outer loop
do
   Statement(s) to be executed if command1 is true

   while command2 ; # this is loop2, the inner loop
   do
      Statement(s) to be executed if command2 is true
   done

   Statement(s) to be executed if command1 is true
done

示例

这是一个循环嵌套的简单例子。 让我们在您用来数到九的循环中添加另一个倒计时循环 −

#!/bin/sh

a=0
while [ "$a" -lt 10 ]    # this is loop1
do
   b="$a"
   while [ "$b" -ge 0 ]  # this is loop2
   do
      echo -n "$b "
      b=`expr $b - 1`
   done
   echo
   a=`expr $a + 1`
done

这将产生以下结果。 重要的是要注意 echo -n 在这里是如何工作的。 这里的 -n 选项让 echo 避免打印换行符。

0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0