Linux Shell编程从初学到精通-循环与结构化命令


循环与结构化命令

最近正在看LinuxShell编程从初学到精通这本书,写的很详细,每一章节后面都有对应的习题,自己也亲手写了下,还有一部分没有写出来,不过正在努力。学习东西要学无止境,循序渐进,希望大家帮助优化下,或者给出更好的建议,谢谢支持!

1、使用for 循环计算100以内所有偶数的和,然后用while循环和until循环来实现这个计算,比较哪种结构更简单;
 
for:
 
 
 
#!/bin/bash
 
#
 
#In addition to sum assigned value
 
sum=0
 
#Use the list for circulation calculated from 1 to 100 of all the sum of, and the value stored in sum
 
for i in {0..100..2}
 
do
 
#    echo $i
 
    let "sum+=i"
 
#    echo $sum
 
done
 
echo "sum=$sum"
 
 
 
while:
 
 
 
 
 
#!/bin/bash
 
#
 
#In addition to sum assigned value
 
sum=0
 
i=0
 
#The use of counter control while circulation calculated from 1 to 100 of all the sum of, and the value stored in sum
 
while (( i <= 100 ))
 
do
 
    let "sum+=i"
 
    echo "sum=$sum"
 
    let "i+=2"
 
    echo "i=$i"
 
done
 
echo "sum=$sum"
 
 
 
until:
 

 

#!/bin/bash
 
#
 
#In addition to sum assigned value
 
sum=0
 
i=0
 
#The use of counter control while circulation calculated from 1 to 100 of all the sum of, and the value stored in sum
 
until (( i > 100 ))
 
do
 
    let "sum+=i"
 
    echo "sum=$sum"
 
    let "i+=2"
 
    echo "i=$i"
 
done
 
echo "sum=$sum"

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 下一页

相关内容