zoukankan      html  css  js  c++  java
  • shell脚本(9)-流程控制for

    一、循环介绍

    for循环叫做条件循环,或者for i in,可以通过for实现流程控制

     

    二、for语法

    1、for语法一:for in

    for var in value1 value2 ......
        do
            commands
    done

    举例说明:输出1到10

    [root@localhost test20210726]# vim for1test.sh
    
    #!/usr/bin/bash
    for i in `seq 1 10`
        do
            echo $i
    done

    查看运行结果:

    [root@localhost test20210726]# sh for1test.sh 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    2、for语法二:for  by c语言

    for ((变量;条件;自增自减运算))do
            commands
    done

    举例说明:输出1到10

    [root@localhost test20210726]# vim for2test.sh 
    
    #!/usr/bin/bash
    
    for ((i=1;i<=10;i++))
        do
            echo $i
    done

    查看运行结果:

    [root@localhost test20210726]# sh for2test.sh 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    3、for语法三:for多个变量

    [root@localhost test20210726]# vim for3test.sh
    
    #!/usr/bin/bash
    
    for ((a=0,b=9;a<10;a++,b--))
        do
            echo $a $b
    done

    查看运行结果:

    [root@localhost test20210726]# sh for3test.sh 
    0 9
    1 8"I
    we km eqg tg00 v6
    4 5iu78
    5 4
    6 3
    7 2
    8 1
    9 0

     

    三、循环控制

    1、sleep:睡眠+秒

    [root@localhost test20210727]# vim testsleep.sh
    
    #!/usr/bin/bash
    
    for var in 1 2 3 4 5 6 7 8 9
      do
        echo $var
        sleep 1
    done

    查看运行结果:(每隔一秒打印一个数字)

    [root@localhost test20210727]# sh testsleep.sh 
    1
    2
    3
    4
    5
    6
    7
    8
    9

    2、continue:跳过循环中的某次循环

    [root@localhost test20210728]# vim continue.sh
    
    #!/usr/bin/bash
    
    #输出 1 2 3 4 6 7 8 9
    for ((i=1;i<10;i++))
      do
        if [ $i -eq 5 ];then
          continue
        fi
        echo $i
    done

    查看运行结果:

    [root@localhost test20210728]# sh continue.sh 
    1
    2
    3
    4
    6
    7
    8
    9

     3、break:跳出循环继续执行后续代码

    [root@localhost test20210728]# vim break.sh 
    
    #!/usr/bin/bash
    
    #输入 1 2 3 4 5 
    for ((i=1;i<10;i++));do
      echo -n $i" "
      if [ $i -eq 5 ]
        then
          break;
      fi
    done

    查询运行结果:

    [root@localhost test20210728]# sh break.sh 
    1 2 3 4 5 
  • 相关阅读:
    Go笔记-接口(interface)
    Go学习笔记-结构体中的方法
    Go学习笔记-数组和切片
    处理器的工作流程
    MySQL重温笔记-索引
    Mysql中为什么应该尽量避免使列默认值为NULL
    which、whereis、find的区别
    linux下查找大文件和大目录
    【转】Linux设置定时任务方法
    [转]python中np.multiply()、np.dot()和星号(*)三种乘法运算的区别
  • 原文地址:https://www.cnblogs.com/mrwhite2020/p/15017985.html
Copyright © 2011-2022 走看看