shell条件判断

使用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:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值