shell流程控制-while循环

 

 

 

一、while介绍

 

特点:条件为真就进入循环;条件为假就退出循环,一般应用在未知循环次数的环境。

 

二、while循环语法

 

while [ 表达式 ]  (注意:条件为真时while才会循环,条件为假,while循环终止,条件中可以是五大运算)
	do
		command...
	done
	
while  [ 1 -eq 1 ]    或者 (( 1 > 2 ))
  do
     command
     command
     ...
 done

 

补充:

如何给一段代码注释起来:

例如:

a1(){

command

}

 

 

 

三、while循环控制与语句嵌套

 

例1:打印1-9,当数值为5时停止循环

 

#!/bin/bash

i=1
while [ $i -lt 10 ]
    do
        echo $i
        if [ $i -eq 5 ];then
           continue
        fi
        i=$((i+1))
done

例2:打印1-9,当数值为5时跳过当前循环


#!/bin/bash

i=1
while [ $i -lt 10 ]
    do
        i=$((i+1))
        if [ $i -eq 5 ]; then
         continue
        fi
        #如何i=10,停止输出
        if [ $i -eq 10 ] ;then
        break
        else
        echo $i
        fi
done


例3:打印九九乘法表

 

#!/bin/bash

n=1

while [ $n -lt 10 ] ;do
    for (( m=1;m<=$n;m++ )) ;do
    echo -n -e "$n * $m =$(( n*m )) \t"
    done
    echo
    n=$((n+1))
done

 

posted @   屯子里唯一的架构师  阅读(298)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示