首页 > 代码库 > linux中的嵌套循环

linux中的嵌套循环

嵌套循环(内循环):一条循环语句可以在循环中使用任何类型的命令,包括其他循环命令

示例1:

#!/bin/bash

for (( a = 1; a <= 3; a++ ))

do

 echo "Starting loop $a"

 for (( b = 1; b <= 3; b++ ))

 do

 echo "Inside loop $b"

done

done

[root@localhost ~]# ./test14.sh 

Starting loop 1

Inside loop 1

Inside loop 2

Inside loop 3

Starting loop 2

Inside loop 1

Inside loop 2

Inside loop 3

Starting loop 3

Inside loop 1

Inside loop 2

Inside loop 3


示例2:

#!/bin/bash

var1=3

while [ $var1 -ge 0 ]

do

echo "Outer loop:$var1"

for (( var2 = 1; $var2 < 3; var2++ ))

do

var3=$[ $var1 * $var2 ]

echo "Inner loop:$var1 * $var2 = $var3"

done

var1=$[ $var1 -1 ]

done

[root@localhost ~]# ./test15.sh 

Outer loop:3

Inner loop:3 * 1 = 3

Inner loop:3 * 2 = 6

Outer loop:2

Inner loop:2 * 1 = 2

Inner loop:2 * 2 = 4

Outer loop:1

Inner loop:1 * 1 = 1

Inner loop:1 * 2 = 2

Outer loop:0

Inner loop:0 * 1 = 0

Inner loop:0 * 2 = 0


示例3:

#!/bin/bash

var1=3

until [ $var1 -eq 0 ]

do

 echo"Outer loop:$var1"

 var2=1

 while [ $var2 -lt 5 ]

do

 var3=`echo "scale=4; $var1 / $var2" | bc`

 echo "Inner loop:$var1 / $var2 = $var3"

 var2=$[ $var2 + 1 ]

done

 var1=$[ $var1 -1 ]

done

[root@localhost ~]# ./test16.sh 

./test16.sh: line 5: echoOuter loop:3: command not found

Inner loop:3 / 1 = 3.0000

Inner loop:3 / 2 = 1.5000

Inner loop:3 / 3 = 1.0000

Inner loop:3 / 4 = .7500

./test16.sh: line 5: echoOuter loop:2: command not found

Inner loop:2 / 1 = 2.0000

Inner loop:2 / 2 = 1.0000

Inner loop:2 / 3 = .6666

Inner loop:2 / 4 = .5000

./test16.sh: line 5: echoOuter loop:1: command not found

Inner loop:1 / 1 = 1.0000

Inner loop:1 / 2 = .5000

Inner loop:1 / 3 = .3333

Inner loop:1 / 4 = .2500



本文出自 “linux运维分享” 博客,请务必保留此出处http://liangey.blog.51cto.com/9097868/1574039

linux中的嵌套循环