1. for命令
for var in list
do
commands
done
for test in monday tuesday wednesday thursday friday saturday sunday
do
echo the test is $test
done
wang@wang:~$ ./test.sh
the test is monday
the test is tuesday
the test is wednesday
the test is thursday
the test is friday
the test is saturday
the test is sunday
2. 用通配符读取目录
for file in /home/wang/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi
done
wang@wang:~$ ./test.sh
/home/wang/90 is a file
/home/wang/a.txt is a file
/home/wang/b.txt is a file
/home/wang/codes is a directory
/home/wang/empty.c is a file
3. C风格for命令
for后面需要使用双括号
for (( a = 1; a < 10; a++ ))
do
echo "The number is $a"
done
4. while 命令
while test command
do
other commands
done
val=10
while [ $val -gt 0 ]
do
echo $val
val=$[$val - 1]
done
val=10
使用多个测试条件,只有最后一个状态码决定循环什么时候结束
while echo $val
[ $val -ge 0 ]
do
echo "This is inside the loop"
val=$[$val - 1]
done
wang@wang:~$ ./test.sh
10
This is inside the loop
9
This is inside the loop
8
This is inside the loop
7
This is inside the loop
6
This is inside the loop
5
This is inside the loop
4
This is inside the loop
3
This is inside the loop
2
This is inside the loop
1
This is inside the loop
0
This is inside the loop
-1
5. until命令
until test commands
do
other commands
done
val=10
until [ $val -le 0 ]
do
echo $val
val=$[ $val - 2 ]
done
wang@wang:~$ ./test.sh
10
8
6
4
2
6. break命令
for (( a = 10; a >= 0; a--))
do
echo "$a"
if [ $a == 5 ]
then
break
fi
done
wang@wang:~$ ./test.sh
10
9
8
7
6
5
跳出内部循环
for (( a = 1; a < 4; a++))
do
echo "Outer loop: $a"
for (( b = 1; b < 100; b++ ))
do
echo "Inside loop: $b"
if [ $b -eq 5 ]
then
break
fi
done
done
wang@wang:~$ ./test.sh
Outer loop: 1
Inside loop: 1
Inside loop: 2
Inside loop: 3
Inside loop: 4
Inside loop: 5
Outer loop: 2
Inside loop: 1
Inside loop: 2
Inside loop: 3
Inside loop: 4
Inside loop: 5
Outer loop: 3
Inside loop: 1
Inside loop: 2
Inside loop: 3
Inside loop: 4
Inside loop: 5
跳出外部循环,与上一个脚本不同处,此次为"break 2"
for (( a = 1; a < 4; a++))
do
echo "Outer loop: $a"
for (( b = 1; b < 100; b++ ))
do
echo "Inside loop: $b"
if [ $b -eq 5 ]
then
break 2
fi
done
done
wang@wang:~$ ./test.sh
Outer loop: 1
Inside loop: 1
Inside loop: 2
Inside loop: 3
Inside loop: 4
Inside loop: 5
7. continue命令
for (( a = 1; a < 10; a++))
do
if [ $a -gt 5 ]
then
continue
fi
echo "loop: $a"
done
wang@wang:~$ ./test.sh
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5