1. 循环
shell循环,不断执行某段程序,直到符合条件。
循环分为4种, while循环,until循环,for固定处理, for数值处理。
2. while循环
while循环是一直执行,直到条件不符合,才停止。
语法:
while [ condition ]
do
//do something
done
例: 循环直到用户输入正确
#!/bin/bash # desc : while loop while [ "$yn" != "yes" -a "$yn" != "YES" ] do read -p "Please input yes/YES to stop : " yn done echo "OK"
执行结果:
[[email protected] sh]$ sh while.sh Please input yes/YES to stop : no Please input yes/YES to stop : yes OK [[email protected] sh]$
例:从1加到100
#!/bin/bash # desc : while loop sum=0 i=0 while [ $i -lt 100 ] do i=$(($i+1)); sum=$(($sum+$i)) done echo "From 1 to 100, sum is : " $sum
3. until循环
until循环和while相反,当条件condition成立时,终止循环。
语法:
until [ condition ]
do
//do something
done
例:
#!/bin/bash # desc : while loop until [ "$yn" == "yes" -o "$yn" == "YES" ] do read -p "Please input yes/YES to stop : " yn done echo "OK"
执行:
[[email protected] sh]$ sh while.sh Please input yes/YES to stop : hi Please input yes/YES to stop : yes OK [[email protected] sh]$
4. for固定循环
for为已知次数的循环。
语法:
for var in con1 con2 ..
do
//do something
done
例:
#!/bin/bash # desc : for loop for animal in dog cat pig do echo "HI, ${animal}" done
执行:
[[email protected] sh]$ sh for.sh HI, dog HI, cat HI, pig [[email protected] sh]$
例:当前目录文件
#!/bin/bash # desc : for loop filelist=$(ls) for filename in $filelist do echo $filename done
5. for数值循环
for数值循环,适用于循环数值计算。
语法
for (( 初始值; 限制值; 步长))
do
// do something
done
例:
#!/bin/bash # desc : for loop sum=0 for (( i=0; i<=100; i++ )) do sum=$(($sum+$i)) done echo "sum is : " $sum
地址:http://blog.csdn.net/yonggang7/article/details/40679701
时间: 2024-10-11 08:40:58