Nested loops (inner loop): A loop statement can use any type of command in a loop, including other loop commands
Example 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
[Email protected] ~]#./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
Example 2:
#!/bin/bash
Var1=3
While [$var 1-ge 0]
Do
echo "Outer loop: $var 1"
for ((var2 = 1; $var 2 < 3; var2++))
Do
var3=$[$var 1 * $var 2]
echo "Inner loop: $var 1 * $var 2 = $var 3"
Done
var1=$[$var 1-1]
Done
[Email protected] ~]#./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
Example 3:
#!/bin/bash
Var1=3
Until [$var 1-eq 0]
Do
echo "Outer loop: $var 1"
Var2=1
While [$var 2-lt 5]
Do
Var3= ' echo ' scale=4; $var 1/$var 2 "| BC '
echo "Inner loop: $var 1/$var 2 = $var 3"
var2=$[$var 2 + 1]
Done
var1=$[$var 1-1]
Done
[Email protected] ~]#./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
This article is from the Linux Operations sharing blog, so be sure to keep this source http://liangey.blog.51cto.com/9097868/1574039
Nested loops in Linux