C语言式的for循环
用法
exp1 exp2 exp3 是三个表达式,其中exp2是判断条件,for循环根据exp2的结果来决定是否继续下一次的循环;
statements是循环体语句,可以有一条,也可以有多条;
do和done是shell中的关键字。
运行过程
1.先执行exp1
2.再执行exp2,如果它的判断结果成立,则执行循环体中的语句,否则结束整个循环
3.执行完循环体再执行exp3
4.重复执行步骤2和3,知道exp2的判断结果不成立,就结束循环
for((exp1;exp2;exp3)) do statements done
1.计算1到100的和
[root@localhost for]# cat 01.sh
#!/bin/bash
sum=0
for ((i=1;i<=100;i++))
do
((sum+=i))
done
echo “The sum is:$sum”
[root@localhost for]# sh 01.sh
The sum is:5050
for ((初始化语句;判断条件;自增或自减)) do statements done
2.省略exp1
注意:
; 不能省略[root@localhost for]# cat 02.sh
#!/bin/bash
i=1
sum=0
for ((;i<=100;i++))
do
((sum+=i))
done
echo “The sum is:$sum”
[root@localhost for]# sh 02.sh
The sum is:5050
3. 省略exp2
[root@localhost for]# cat 03.sh
#!/bin/bash
sum=0
for ((i=1; ;i++))
do
if ((i>100));then
break
fi
((sum+=i))
done
echo “The sum is:$sum”
[root@localhost for]# sh 03.sh
The sum is:5050
4. 省略exp3
[root@localhost for]# cat 04.sh
#!/bin/bash
sum=0
for ((i=1; i<=100;))
do
((sum+=i))
((i++))
done
echo “The sum is:$sum”
[root@localhost for]# sh 04.sh
The sum is:5050
5. 省略exp1~3
[root@localhost for]# cat 05.sh
#!/bin/bash
i=0
sum=0
for ((;;))
do
if ((i>100));then
break
fi
((sum+=i))
((i++))
done
echo “The sum is:$sum”
[root@localhost for]# sh 05.sh
The sum is:5050