Unix / Linux - Shell循环类型

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

  • while循环

  • The for循环

  • 直到循环

  • 选择循环

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

一旦你有良好的编程习惯,你将获得专业知识,从而开始使用适当的循环基于情况.在这里, for 循环可用于大多数其他编程语言,如 C C ++ PERL 等.

嵌套循环

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

以下是嵌套 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