Shell 流程控制 - while 循环

Shell 流程控制 - while 循环


简介

  • while 循环用于不断执行一系列命令,也用于从输入文件中读取数据。

  • ’ while ’ 后为循环执行的条件,为 " true " 或者 " : " 时,便是无限循环。

  • 循环的退出:

    • ’ continue ':终止当此次前循环提前进入下个循环 。
    • ’ break ’ :终止当前所在语句所有动作进行语句外的其他动作 。
    • ’ exit ’ :脚本退出 。
  • ’ do ’ :后面为循环要执行的命令。

  • ’ done ’ :循环结构结束的标志。

  • 语法格式

    while condition
    do
        command
    done
    
  • 写成一行

    while test-commands; do consequent-commands; done
    

参考文章


示例

  • 无限循环示例: 判断文件类型,直到输入 ’ exit ’ 退出。
    [root@ while]# cat check_file.sh 
    #!/bin/bash
    while :
    do
      read -p "input file: " file
      if [ $file = "exit" ]
      then
        exit
      else
        echo "$file is `file $file | awk -F ":" '{print $2}'`"
      fi
    done
    [root@ while]# sh check_file.sh 
    input file: test.sh
    test.sh is  Bourne-Again shell script, ASCII text executable
    input file: ../while
    ../while is  directory
    input file: /root
    /root is  directory
    input file: /dev/null
    /dev/null is  character special
    input file: exit
    [root@ while]#                   
    
  • 有限循环:打印一到五。
    [root@ while]# cat test.sh 
    #!/bin/bash
    int=1
    while (( $int<=5 ))
    do
        echo $int
        let "int++"
    done 
    [root@ while]# sh test.sh 
    1
    2
    3
    4
    5
    [root@ while]
    



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值