• 【Shell】Shell编程之while循环命令


    语法结构

    while命令的基本格式:
    while test command
    do
        other commands
    done


    计数器控制的While循环

    示例1、打印小于等于10的数
    [root@strong bash_stu]# cat test2.sh 
    #!/bin/bash
    
    i=1
    while [ $i -lt 10 ]
    do
      echo $i
      i=$(($i+1))
    done
    [root@strong bash_stu]# . test2.sh 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    [root@strong bash_stu]# 
    示例2、计算1~100内的奇数和
    [root@strong shell_stu]# cat test.sh 
    #!/bin/bash
    
    sum=0
    i=1
    
    while [ $i -lt 100 ]
    do
      sum=$(($sum+$i))
      i=$(($i+2))
    done
    echo "1+3+5+...+100="$sum
    [root@strong shell_stu]# . test.sh 
    1+3+5+...+100=2500
    --或者
    [root@strong shell_stu]# cat while.sh 
    #!/bin/bash
    
    sum=0
    i=1
    
    while ((i <= 100))
    do
      let "sum+=i"
      let "i+=2"
    done
    echo "1+3+3+..."=$sum
    [root@strong shell_stu]# . while.sh 
    1+3+3+...=2500

    结束标记控制的while循环

    在Linux SHELL编程中,如果不指定读入数据的个数,可以设置一个特殊的数据值来结束while循环,该特殊数据值称为结束标志。其通过提示用户输入特殊字符或数字来操作,当用户输入该标记后结束while循环,执行done后的命令,while循环的形式如下:
    read variable
    while [[ "$variable"!=sentline1]]
    do
         read variable
    done

    示例:
    [root@strong ~]# cat while_01.sh 
    #!/bin/bash
    
    echo "Please enter a number(1~10)"
    
    read num
    
    while [[ "$num"!=4 ]]
    do
      if [ "$num" -lt 4 ]
      then
         echo "Too small , try again"
         read num
      elif [ "$num" -gt 4 ]
      then
         echo "Too great, try again"
         read num
      else
        # exit 0
        break
      fi
    done
    
    echo "Congratulation ,you are right"
    [root@strong ~]# . while_01.sh 
    Please enter a number(1~10)
    3
    Too small , try again
    5
    Too great, try again
    4
    Congratulation ,you are right


  • 相关阅读:
    二维码生成:使用 JavaScript 库QRCode.js生成二维码
    VC++6.0远程调试(亲试成功)
    Linux同时安装python2和Python3
    Python打包-py2exe
    camera按键采集图像及waitKey的用法(转)
    ucos实时操作系统学习笔记——任务间通信(信号量)(转)
    STM32硬件IIC驱动设计(转)
    基于STM32F4移植W5500官方驱动库ioLibrary_Driver(转)
    USB基础知识概论(版本:v0.9.2)
    usb帧格式
  • 原文地址:https://www.cnblogs.com/alen-liu-sz/p/12975666.html
Copyright © 2020-2023  润新知