使用if进行判断:类似于C语言中的if,使用[]代替了(),结束时,需要加fi,
#! /bin/bash
read num
if [ "$num" -gt 20 ];then
echo "此数大于20"
fi
同样也可以使用else进行嵌套判断
#! /bin/bash
#输出提示信息
echo "Please enter a score:"
#读取用户输入数据
read score
#如果用户没有输入数据,则提示用户重新输入
if [ -z "$score" ]; then
echo "You enter nothing.Please enter a score:"
read score
else
#如果用户输入的数据不对,则重新输入
if [ "$score" -lt 0 -o "$score" -gt 100 ]; then
echo "The score should be between 0 and 100.Please enter again:"
read score
else
#输出级别A
if [ "$score" -ge 90 ]; then
echo "The grade is A."
else
#输出级别B
if [ "$score" -ge 80 ]; then
echo "The grade is B."
else
#输出级别C
if [ "$score" -ge 70 ]; then
echo "The grade is C."
else
#输出级别D
if [ "$score" -ge 60 ]; then
echo "The grade is D."
else
#输出级别E
echo "The grade is E."
fi
fi
fi
fi
fi
fi
或者使用if elfi更加清晰明了
#! /bin/bash
echo "Please enter a score:"
read score
if [ -z "$score" ]; then
echo "You enter nothing.Please enter a score:"
read score
else
if [ "$score" -lt 0 -o "$score" -gt 100 ]; then
echo "The score should be between 0 and 100.Please enter again:"
read score
else
#如果成绩大于90
if [ "$score" -ge 90 ]; then
echo "The grade is A."
#如果成绩大于80且小于90
elif [ "$score" -ge 80 ]; then
echo "The grade is B."
#如果成绩大于70且小于80
elif [ "$score" -ge 70 ]; then
echo "The grade is C."
#如果成绩大于60且小于70
elif [ "$score" -ge 60 ]; then
echo "The grade is D."
#如果成绩小于60
else
echo "The grade is E."
fi
fi
fi
多条件判断语句case: