case条件语句

元气小坏坏 提交于 2020-01-19 22:57:28

case条件语句的语法格式:

case "变量" in 

   值1)

          指令1........

           ;;

值2)

          指令2........

           ;;

*)

          指令3........

    esac

举例1:

输入1-9,输出1-9;输出其他,退出

#!/bin/bash
read -p "Please input a number:" ans 
case "$ans" in 
  [1-9])
    echo "The num you input is $ans"
    ;;
  *)
    echo "Please input [0-9] int"
    exit
esac

举例2:

#!/bin/bash
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'
echo '
  ==================
  1.apple
  2.pear
  3.banana
  4.cherry
  ==================
'
read -p "Please select a number:" num 
case "$num" in 
  1)
    echo -e "$RED_COLOR apple $RES"
    ;;
  2)
    echo -e "$GREEN_COLOR pear $RES"
    ;;
  3)
    echo -e "$YELLOW_COLOR banana $RES"
    ;;
  4)
    echo -e "$BLUE_COLOR cherry $RES"
    ;;
  *)
    echo "muse be {1|2|3|4}"
esac

更加专业点,写成函数

#!/bin/bash
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'
function menu(){
  cat <<END
  1.apple
  2.pear
  3.banana
  4.cherry
END
}
function chose(){
read -p "Please select a number:" num 
case "$num" in 
  1)
    echo -e "$RED_COLOR apple $RES"
    ;;
  2)
    echo -e "$GREEN_COLOR pear $RES"
    ;;
  3)
    echo -e "$YELLOW_COLOR banana $RES"
    ;;
  4)
    echo -e "$BLUE_COLOR cherry $RES"
    ;;
  *)
    echo "muse be {1|2|3|4}"
esac
}
function main(){
 menu
 chose
}
main

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!