码迷,mamicode.com
首页 > 系统相关 > 详细

shell循环loop

时间:2014-11-01 14:58:02      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:shell   loop   while   until   for   

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"
执行结果:
[work@www sh]$ sh while.sh 
Please input yes/YES to stop : no
Please input yes/YES to stop : yes
OK
[work@www 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"
执行:
[work@www sh]$ sh while.sh 
Please input yes/YES to stop : hi         
Please input yes/YES to stop : yes
OK
[work@www 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
执行:
[work@www sh]$ sh for.sh 
HI, dog
HI, cat
HI, pig
[work@www 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


shell循环loop

标签:shell   loop   while   until   for   

原文地址:http://blog.csdn.net/yonggang7/article/details/40679701

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!