zoukankan      html  css  js  c++  java
  • shell浅谈之三for、while、until循环【转】

     
     

    一、简介

          Shell编程中循环命令用于特定条件下决定某些语句重复执行的控制方式,有三种常用的循环语句:for、while和until。while循环和for循环属于“当型循环”,而until属于“直到型循环”。循环控制符:break和continue控制流程转向。

    二、详解

    1、for循环

    (1)for循环有三种结构:一种是列表for循环,第二种是不带列表for循环。第三种是类C风格的for循环。

    (2)列表for循环

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. for varible1 in {1..5}  
    4. #for varible1 in 1 2 3 4 5  
    5. do  
    6.      echo "Hello, Welcome $varible1 times "  
    7. done  
    • do和done之间的命令称为循环体,执行次数和list列表中常数或字符串的个数相同。for循环,首先将in后list列表的第一个常数或字符串赋值给循环变量,然后执行循环体,以此执行list,最后执行done命令后的命令序列。
    • Sheel支持列表for循环使用略写的计数方式,1~5的范围用{1..5}表示(大括号不能去掉,否则会当作一个字符串处理)。
    • Sheel中还支持按规定的步数进行跳跃的方式实现列表for循环,例如计算1~100内所有的奇数之和。      
    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2. sum=0  
    3.   
    4. for i in {1..100..2}  
    5. do  
    6.     let "sum+=i"  
    7. done  
    8.       
    9. echo "sum=$sum"  
          通过i的按步数2不断递增,计算sum值为2500。同样可以使用seq命令实现按2递增来计算1~100内的所有奇数之和,for i in $(seq 1 2 100),seq表示起始数为1,跳跃的步数为2,结束条件值为100。
    • for循环对字符串进行操作,例如通过for循环显示当前目录下所有的文件。
    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. for file in $( ls )  
    4. #for file in *  
    5. do  
    6.    echo "file: $file"  
    7. done  

    也可一使用for file in *,通配符*产生文件名扩展,匹配当前目录下的所有文件。

    • for通过命令行来传递脚本中for循环列表参数
    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. echo "number of arguments is $#"  
    4.   
    5. echo "What you input is: "  
    6.   
    7. for argument in "$@"  
    8. do  
    9.     echo "$argument"  
    10. done  

    $#表示参数的个数,$@表示参数列表而$*则把所有的参数当作一个字符串显示。

    (3)不带列表for循环

    由用户制定参数和参数的个数,与上述的for循环列表参数功能相同。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. echo "number of arguments is $#"  
    4.   
    5. echo "What you input is: "  
    6.   
    7. for argument  
    8. do  
    9.     echo "$argument"  
    10. done  
    比上述代码少了$@参数列表,$*参数字符串。

    (4)类C风格的for循环

    也被称为计次循环

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. for((integer = 1; integer <= 5; integer++))  
    4. do  
    5.     echo "$integer"  
    6. done  

          for中第一个表达式(integer = 1)是循环变量赋初值的语句,第二个表达式(integer <= 5)决定是否进行循环的表达式,退出状态为非0时将退出for循环执行done后的命令(与C中的for循环条件是刚好相反的)。第三个表达式(integer++)用于改变循环变量的语句。

          Sheel中不运行使用非整数类型的数作为循环变量,循环条件被忽略则默认的退出状态是0,for((;;))为死循环。

           类C的for循环计算1~100内所有的奇数之和。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. sum=0  
    4.   
    5. for(( i = 1; i <= 100; i = i + 2 ))  
    6. do  
    7.      let "sum += i"  
    8. done  
    9.   
    10. echo "sum=$sum"  

    2、while循环

           也称为前测试循环语句,重复次数是利用一个条件来控制是否继续重复执行这个语句。为了避免死循环,必须保证循环体中包含循环出口条件即表达式存在退出状态为非0的情况。

    (1)计数器控制的while循环

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. sum=0  
    4.   
    5. i=1  
    6.   
    7. while(( i <= 100 ))  
    8. do  
    9.      let "sum+=i"  
    10.      let "i += 2"     
    11. done  
    12.   
    13. echo "sum=$sum"  
          指定了循环的次数500,初始化计数器值为1,不断测试循环条件i是否小于等于100。在循环条件中设置了计数器加2来计算1~100内所有的奇数之和。

    (2)结束标记控制的while循环

    设置一个特殊的数据值(结束标记)来结束while循环。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. echo "Please input the num(1-10) "  
    4. read num  
    5.   
    6. while [[ "$num" != 4 ]]  
    7. do   
    8.    if [ "$num" -lt 4 ]  
    9.    then  
    10.         echo "Too small. Try again!"  
    11.         read num  
    12.    elif [ "$num" -gt 4 ]  
    13.    then  
    14.          echo "To high. Try again"   
    15.          read num  
    16.    else  
    17.        exit 0  
    18.     fi  
    19. done   
    20.   
    21. echo "Congratulation, you are right! "  

    例:通过结束标记控制实现阶乘的操作

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. echo "Please input the num "  
    4. read num  
    5.   
    6. factorial=1  
    7.   
    8. while [ "$num" -gt 0 ]  
    9. do  
    10.     let "factorial= factorial*num"  
    11.     let "num--"  
    12. done  
    13.   
    14. echo "The factorial is $factorial"  

    (3)标志控制的while循环

         使用用户输入的标志值来控制循环的结束(避免不知道循环结束标志的条件)。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. echo "Please input the num "  
    4. read num  
    5.   
    6. sum=0  
    7. i=1  
    8.   
    9. signal=0  
    10.   
    11. while [[ "$signal" -ne 1 ]]  
    12. do  
    13.     if [ "$i" -eq "$num" ]  
    14.     then   
    15.        let "signal=1"  
    16.        let "sum+=i"  
    17.        echo "1+2+...+$num=$sum"  
    18.     else  
    19.        let "sum=sum+i"  
    20.        let "i++"  
    21.     fi  
    22. done  

          标志控制的while循环求1~n的累加和,循环变量值小于100执行else累加同时循环变量加1,直到循环变量值等于100将标志值设置为1,并输出。

          标志控制的while循环与结束标记控制的while循环的区别是用户无法确定无法确定结束标志,只能程序运行后确定结束标志。两者也可以相互转化。

    (4)命令行控制的while循环
          使用命令行来指定输出参数和参数个数,通常与shift结合使用,shift命令使位置变量下移一位($2代替$1、$3代替$2,并使$#变量递减),当最后一个参数显示给用户,$#会等于0,$*也等于空。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. echo "number of arguments is $#"  
    4.   
    5. echo "What you input is: "  
    6.   
    7. while [[ "$*" != "" ]]  
    8. do  
    9.     echo "$1"  
    10.     shift  
    11. done  

    循环条件可以改写为while[[ "$#" -ne 0 ]],等于0时退出while循环

    3、until循环

          until命令和while命令类似,while能实现的脚本until同样也可以实现,但区别是until循环的退出状态是不为0,退出状态是为0(与while刚好相反),即whie循环在条件为真时继续执行循环而until则在条件为假时执行循环。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. i=0  
    4.   
    5. until [[ "$i" -gt 5 ]]    #大于5  
    6. do  
    7.     let "square=i*i"  
    8.     echo "$i * $i = $square"  
    9.     let "i++"  
    10. done  

    4、循环嵌套

    一个循环体内又包含另一个完整的循环结构,在外部循环的每次执行过程中都会触发内部循环,for、while、until可以相互嵌套。

    (1)嵌套循环实现九九乘法表

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. for (( i = 1; i <=9; i++ ))  
    4. do  
    5.       
    6.     for (( j=1; j <= i; j++ ))  
    7.     do  
    8.         let "temp = i * j"       
    9.         echo -n "$i*$j=$temp  "  
    10.      done   
    11.        
    12.      echo ""   #output newline  
    13. done  

    (2)for循环嵌套实现*图案排列

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. for ((i=1; i <= 9; i++))  
    4. do  
    5.     j=9;  
    6.     while ((j > i))  
    7.     do  
    8.         echo -n " "  
    9.         let "j--"  
    10.     done  
    11.     k=1  
    12.     while ((k <= i))  
    13.     do  
    14.         echo -n "*"  
    15.         let "k++"  
    16.     done  
    17.     echo ""  
    18. done  

    外层for循环嵌套了两个内层while循环,先打印空格在打印*号形成图案。

    5、循环控制符break和continue

    若须退出循环可使用break循环控制符,若退出本次循环执行后继续循环可使用continue循环控制符。

    (1)break

        在for、while和until循环中break可强行退出循环,break语句仅能退出当前的循环,如果是两层循环嵌套,则需要在外层循环中使用break。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. sum=0  
    4. for (( i=1; i <= 100; i++))  
    5. do   
    6.     let "sum+=i"  
    7.   
    8.     if [ "$sum" -gt 1000 ]  
    9.     then  
    10.         echo "1+2+...+$i=$sum"  
    11.         break  
    12.     fi  
    13. done  

    (2)continue

    在for、while和until中用于让脚本跳过其后面的语句,执行下一次循环。continue用于显示100内能被7整除的数。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. m=1  
    4. for (( i=1; i < 100; i++ ))  
    5. do  
    6.     let "temp1=i%7"         #被7整除  
    7.    
    8.     if [ "$temp1" -ne 0 ]  
    9.     then  
    10.         continue  
    11.     fi  
    12.       
    13.     echo -n "$i  "  
    14.       
    15.     let "temp2=m%7"          #7个数字换一行  
    16.       
    17.     if  [ "$temp2" -eq 0 ]  
    18.     then  
    19.         echo ""  
    20.     fi  
    21.       
    22.     let "m++"  
    23. done  

    6、select结构

          select结构从技术角度看不能算是循环结构,只是相似而已,它是bash的扩展结构用于交互式菜单显示,功能类似于case结构比case的交互性要好。

    (1)select带参数列表

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. echo "What is your favourite color? "  
    4.   
    5. select color in "red" "blue" "green" "white" "black"  
    6. do   
    7.     break  
    8. done  
    9.   
    10. echo "You have selected $color"  

    (2)select不带参数列表

    该结构通过命令行来传递参数列表,由用户自己设定参数列表。

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #!/bin/bash  
    2.   
    3. echo "What is your favourite color? "  
    4.   
    5. select color  
    6. do   
    7.     break  
    8. done  
    9.   
    10. echo "You have selected $color"  

    三、总结

    (1)循环结构中相互嵌套组成更复杂的流程,并结合break和continue可以实现很多复杂的运算。

    (2)可以结合其他语言的语法有助于更好的理解循环结构。

    (3)熟练应用还需要大量的重复练习,重写优秀的shell代码也是一种很好的方式。

  • 相关阅读:
    win10安装完Ubuntu后重启没有引导页面,直接进入Windows的解决办法 标签: ubuntu 2017-07-02 16:04 41人阅读
    Python小项目三:用curses实现2048 标签: 2048python实验楼游戏 2017-07-01 22:12 50人阅读 评
    Python小项目四:实现简单的web服务器 标签: web服务器网络编程python 2017-06-30 21:43 57人阅读 评论
    英语魔法师之语法俱乐部阅读笔记 标签: 语法俱乐部英语语法 2017-06-30 15:17 24人阅读 评论(0)
    Good Features to track特征点检测原理与opencv(python)实现 标签: pythonopencvgoodfeaturetotrack 2017-06-16 1
    Harris角点检测原理与opencv(python)实现 标签: harris特征点检测角点检测opencv 2017-06-14 19:01 65人阅读
    python “ImportError: No module named XXX”的解决方案 标签: importErrorpython 2017-06-13 15:14
    python小项目二:图片转字符画 标签: pythonPIL 2017-06-12 10:26 19人阅读 评论(0)
    python小项目一:NBA比赛数据分析 标签: python数据分析csv 2017-06-10 20:18 29人阅读 评论(0)
    ubuntu安装卸载遇到的诸多问题 标签: ubuntuwindows 7 2017-06-06 21:08 54人阅读 评论(0)
  • 原文地址:https://www.cnblogs.com/sky-heaven/p/5463242.html
Copyright © 2011-2022 走看看