一. if 判断
语法1:
if [ 条件判断式 ];then
程序
fi
或者:
if [ 条件判断式 ]
then
程序
fi
语法2:
if [ 条件判断式 ]
then
程序1
else
程序2
fi
语法3:
if [ 条件判断式1 ]
then
程序1
elif [ 条件判断式2 ]
then
程序2
elif [ 条件判断式3 ]
then
程序3
else
程序4
fi
实操案例:
#!/bin/bash
echo "Please Input a integer(0-100): "
read score
if [ "$score" -lt 0 -o "$score" -gt 100 ]
then
echo "The score what you input is not integer or the score is not in (0-100)."
elif [ "$score" -ge 90 ]
then
echo "The grade is A!"
elif [ "$score" -ge 80 ]
then
echo "The grade is B!"
elif [ "$score" -ge 70 ]
then
echo "The grade is C!"
elif [ "$score" -ge 60 ]
then
echo "The grade is D!"
else
echo "The grade is E!"
fi
二. case语句
语法:
case $变量名 in
"值1")
如果变量的值等于值1,则执行程序1
;;
"值2")
如果变量的值等于值2,则执行程序2
;;
…省略其他分支…
*)
如果变量的值都不是以上的值,则执行此程序
;;
esac
注意事项:
- case行尾必须为单词“in”,每一个模式匹配必须以右括号“)”结束。
- 双分号“;;”表示命令序列结束,相当于java中的break。
- 最后的“*)”表示默认模式,相当于java中的default。
实操案例:
#!/bin/bash
echo "Please Input a score_type(A-E): "
read score_type
case "$score_type" in
A)
echo "The range of score is from 90 to 100 !";;
B)
echo "The range of score is from 80 to 89 !";;
C)
echo "The range of score is from 70 to 79 !";;
D)
echo "The range of score is from 60 to 69 !";;
E)
echo "The range of score is from 0 to 59 !";;
*)
echo "What you input is wrong !";;
esac
三. for循环
语法:
for (( 初始值;循环控制条件;变量变化 ))
do
程序
done
实操案例:
#!/bin/bash
sum=0
for(( i = 1; i <= 100; i = i + 2 ))
do
let "sum += i"
done
echo "sum=$sum"
四. while循环
语法:
while [ 条件判断式 ]
do
程序
done
实操案例:
#!/bin/bash
sum=0
i=1
while(( i <= 100 ))
do
let "sum+=i"
let "i += 2"
done
echo "sum=$sum"
网友评论