# IFS (internal field separator) to separator string
IFSHOLD=$IFS
IFS=$'\n'
forentry in`cat/etc/passwd`;do
echo"Values in $entry:"
IFS=:
forvalue in$entry;do
echo" $value"
done
done
IFS=$IFSHOLD
2. while loop
Shell
1
2
3
4
5
6
7
#!/bin/bash
var1=10
while[$var1-gt0];do
echo$var1
var1=$[$var1-1]
done
3. until loop
Shell
1
2
3
4
5
6
7
#!/bin/bash
var1=100
until[$var1-eq0];do
echo$var1
var1=$[$var1-25]
done
4. break & continue
Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/bin/bash
# break
for((a=1;a<4;a++));do
echo"Outer loop: $a"
for((b=1;b<100;b++));do
if[$b-eq5];then
break
fi
echo"Inner loop: $b"
done
done
# break outer loop
for((a=1;a<4;a++));do
echo"Outer loop: $a"
for((b=1;b<100;b++));do
if[$b-eq5];then
break2
fi
echo"Inner loop: $b"
done
done
# continue outer loop
for((a=1;a<=5;a++));do
echo"Iteration $a:"
for((b=1;b<3;b++));do
if[$a-gt2]&&[$a-lt4];then
continue2
fi
var3=$[$a*$b]
echo" The result of $a * $b is $var3"
done
done
There may be times when you’re in an inner loop but need to stop the outer loop. The break command includes a single command line parameter value: break n where n indicates the level of the loop to break out of. By default, n is 1, indicating to break out of the current loop. If you set n to a value of 2, the break command will stop the next level of the outer loop.
5. redirect & pipe
Finally, you can either pipe or redirect the output of a loop within your shell script.