- Back to Home »
- Shell »
- Shell - Shell Loops
Sunday, July 12, 2015
1. Shell Loop
1.1 The while loop
Syntax:
while condition
do
Statement(s) to be executed if condition is true
done
or while condition; do
Statement(s) to be executed if condition is true
done
Ex:
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
$./test.sh
0
1
2
3
4
5
6
7
8
9
1.2 The for loop
Syntax:
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Trong đó var là biến thay đổi, nó sẽ lần lượt được gán các giá trị từ word1 -> wordN.Ex1:
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
$./test.sh
0
1
2
3
4
5
6
7
8
9
Ex2:
#!/bin/sh
for FILE in $HOME/.bash*
do
echo $FILE
done
$./test.sh
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc
1.3 The until loop
Syntax:
until condition
do
Statement(s) to be executed until condition is true
done
#!/bin/sh
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
$./test.sh
0
1
2
3
4
5
6
7
8
9
1.4 The select loop
Syntax:
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Ex:
#!/bin/ksh
select DRINK in tea cofee water juice appe all none
do
case $DRINK in
tea|cofee|water|all)
echo "Go to canteen"
;;
juice|appe)
echo "Available at home"
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
#? juice
Available at home
#? none
$
2. Nesting Loops (Vòng lặp lồng nhau)
Syntax:
while condition1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if condition1 is true
while condition2 ; # this is loop2, the inner loop
do
Statement(s) to be executed if condition2 is true
done
Statement(s) to be executed if condition1 is true
done
Ex:
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
$./test.sh
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0