分支结构— if和case

一、if分支:

  单分支:if 判断条件;then

        条件成立则执行的语句

      fi

  双分支:if 判断条件;then

        条件成立则执行的语句

      else

        条件不成立则执行的语句

      fi

  多分支:if 判断条件1;then

        条件1成立则执行的语句

      elif 判断条件2;then

        在条件1不成立下,条件2成立则执行的语句

      elif 判断条件3;then

        在条件1、2都不成下,条件3成立则执行的语句

      ......

      else

        以上条件都不成立则执行的语句

      fi

粗略的BMI测评脚本

#!/bin/bash
#
#*************************************************************
#Author:                         lideyuan
#QQ:                             8888888888
#Date:                           2020-04-24
#FileName:                       if_bim.sh
#URL:                            http://www.lidyeyuan.com
#Description:                    the test script
#Copyright (C):                  2020 All rights reserved
#*************************************************************
read -p "请输入你的身高(m为单位) :" h
if [[ ! $h =~ ^[0-2].?[0-9]{,2}$ ]];then echo "身高输入错误"; exit; fi 
read -p "请输入你的体重(kg为单位):" w
if [[ ! $w =~ ^[0-9]{1,2}[.]?[0-9]?$ ]];then echo "体重输入错误";exit; fi
bmi=`echo "$w/$h^2"|bc`
if [ $bmi -le 18 ];then
    echo "你太瘦了,要多吃点哦"
elif [ $bmi -lt 24  ];then
    echo "身材很棒哦"
else 
    echo "你太胖了,注意节食,加强运动"
fi

 

二、case分支

      case 变量 in 

      范围)

      分支1

      ;;

      ......

      *)

      分支n

      esca

#!/bin/bash
#
#*************************************************************
#Author:                         lideyuan
#QQ:                             8888888888
#Date:                           2020-04-24
#FileName:                       yes_no.sh
#URL:                            http://www.lidyeyuan.com
#Description:                    the test script
#Copyright (C):                  2020 All rights reserved
#*************************************************************
read -p "请输入yes(或者no):" input
input=`echo $input|tr "a-z" "A-Z"`
case $input in 
YES|Y)
    echo "您输入的YES"
    ;;
NO|N)
    echo "您输入的NO"
    ;;
*)
    echo "您输入错误,请输入 yes or no!"
esac

 

posted @ 2020-04-24 18:53  ldyaly  阅读(329)  评论(0编辑  收藏  举报