发布于 2016-10-10 14:54:20 | 180 次阅读 | 评论: 0 | 来源: 网络整理

循环是一个强大的编程工具,使您能够重复执行一组命令。在本教程中,您将学习以下类型的循环Shell程序:

  • while 循环

  • for 循环

  • until 循环

  • select 循环

你会根据不同情况使用不同的循环。例如用 while 循环执行命令,直到给定的条件下是 ture ,循环直到执行到一个给定的条件为 false。

有良好的编程习惯,将开始使用情况的基础上适当的循环。这里while和for循环类似在大多数其他的编程语言,如C,C++ 和 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
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务