shell循环loop

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


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。