[Shell脚本]计算1+2+3+…+100的和并输出
睡前看了下google reader订阅,发现这里有几个题挺有意思。刚学完bash,顺便来练练手。
一、for循环实现
1: #!/bin/bash
2: sum=0
3:
4: for ((i=1;i<=100;i++))
5: do
6: ((sum = sum + i))
7: done
8:
9: echo $sum
运行时间:
1: [root@localhost bash]# time ./sum100.sh
2: 5050
3:
4: real 0m0.008s
5: user 0m0.003s
6: sys 0m0.004s
二、函数递归
1: #!/bin/bash
2: sum=0
3: add ()
4: {
5: local i=$1
6:
7: if [ $i -ne 0 ]
8: then
9: ((sum=sum+$i))
10: add `expr $i - 1`
11: fi
12: }
13:
14: add $1
15: echo $sum
运行时间:
1: [root@localhost bash]# time ./sum.sh 100
2: 5050
3:
4: real 0m0.353s
5: user 0m0.049s
6: sys 0m0.228s