while循环语法

while <条件表达式>

do

指令...

done

until 循环语句语法

until <条件表达式>

do

指令...

done

范例

1、使用while循环竖向打印54321

[root@web1 scripts]# cat test38.sh

#!/bin/bash

i=5                        #因为是从大到小,所以初始化i的值为5

while ((i>0))                  #双小括号条件表达式,当i大于0不成立时就跳出循环

do

echo "$i"                #打印变量i的值

((i--))                 #i的值自减,每次减1

done

[root@web1 scripts]# ./test38.sh

5

4

3

2

1

[root@web1 scripts]#

2、使用双中括号条件表达式

[root@web1 while-until]# cat test39.sh

#!/bin/bash

i=5

while [[ $i > 0 ]]

do

echo $i

((i--))

done

[root@web1 while-until]# ./test39.sh

5

4

3

2

1

[root@web1 while-until]#

3、使用传参需要打印的数字

[root@web1 while-until]# cat test40.sh

#!/bin/bash

i="$1"

while [[ $i -gt 0 ]]

do

echo $i

((i--))

done

[root@web1 while-until]# ./test40.sh 5

5

4

3

2

1

[root@web1 while-until]#

4、使用until语句实现

[root@web1 while-until]# cat test41.sh

#!/bin/bash

i=5

until [[ $i < 1 ]]        #当条件表达式不成立时,进入循环执行命令,因为0<1成立,因此退出循环

do

echo $i

((i--))

done

[root@web1 while-until]# ./test41.sh

5

4

3

2

1

[root@web1 while-until]#

5、计算1加到100之和

[root@web1 while-until]# cat test42.sh

#!/bin/bash

i=1                             #i为自增变量,从1到100,初始值1

sum=0                            #总和变量初始值为0

while ((i<=100))                     #条件是i小于等于100,也就是从1加到100

do

((sum=sum+i))                  #把i的值和当前sum总和的值做加法结果重新赋值给sum

((i++))                      #i每次加1

done

[ "$sum" -ne 0 ] && printf "totalsum is:$sum\n"


[root@web1 while-until]# ./test42.sh

totalsum is:5050

[root@web1 while-until]#

6、通过数学公式实现

[root@web1 while-until]# cat 4-6.sh

#!/bin/bash

i=100

((sum=i*(i+1)/2))              #利用数公式求和公式计算,效率很高

echo $sum

[root@web1 while-until]# ./4-6.sh

5050