14.2.1 if判断结构
if是最简单的判断语句,可以针对测试结果做相应处理:如果测试为真则运行相关代码,其语法结构如下:
- if expression; then
command
fi
如果expression测试返回真,则执行command。如果要执行的不止一条命令,则不同命令间用换行符隔开,如下所示:
- if expression; then
command1
command2
...
fi
下面演示一个程序,该程序会根据输入的学生成绩打印对应的等级:大于等于80分的为A;大于等于60分、小于80分的为B、小于60分的为C。
- [root@localhost ~]# cat score01.sh
#!/bin/bash
echo -n "Please input a score:"
read SCORE
if [ "$SCORE" -lt 60 ]; then
echo "C"
fi
if [ "$SCORE" -lt 80 -a "$SCORE" -ge 60 ]; then
echo "B"
fi
if [ "$SCORE" -ge 80 ]; then
echo "A"
fi
#
脚本运行结果,依次输入95
、75
、45
时,脚本分别打印了正确的成绩等级
[root@localhost ~]# bash score01.sh
Please input a score:95
A
[root@localhost ~]# bash score01.sh
Please input a score:75
B
[root@localhost ~]# bash score01.sh
Please input a score:45
C