shell(九)case

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/wzj_110/article/details/100189781

A case structure conditionals

case statement is actually a standard multi-branch if statement

grammar

    case "字符串变量" in
      值1) 指令1...
    ;;
      值2) 指令2...
    ;;
      *) 指令3...
    esac 

Requirement 1 : The user determines which input numbers. If the user inputs a digital output corresponding to the digital input, if else return Incorrect

#!/bin/bash
#(1)健壮和友好
usage(){
  echo "USAGE:$0 number."
  exit 1
}
#(2)根据输入的数字[0-9]的一位数字输出相应的数字
case_fun(){
  case $1 in
    [1-9])                      # 细细体会!
      echo $1
  ;;
    *)
      echo "input error."
  esac
}
#(3)判断参数的个数
main(){
  case $# in
    1) case_fun $1
  ;;
    *) usage
  esac
}
main $*

Requirement 2:

执行脚本打印一个水果菜单:

1、apple

2、pear

3、banana

4、cherry

当用户选择水果的时候,打印选择水果是什么,并给水果单词加上颜色

specific

#!/bin/bash
# 颜色预定义
RED='\e[1;31m'
GREEN='\e[1;32m'
YELLOW='\e[1;33m'
BLUE='\e[1;34m'
PINK='\e[1;35m'
RES='\e[0m'
# 说明:闪烁警告
FLICKER='\e[31;5m'
usage(){
  echo -e "${FLICKER}Plesae select the exist num behind. ${RES}"
  exit 1
}
choice(){
  case $num in
    1) echo -e "${BLUE}apple${RES}"
  ;;
    2) echo -e "${GREEN}pear${RES}"
  ;;
    3) echo -e "${YELLOW}banana${RES}"
  ;;
    4) echo -e "${RED}cherry${RES}"
  ;;
    *) usage
  esac
}
main(){
  choice $num
}
#(1)先打印菜单-->echo或者cat两种方式
echo "
  1、apple
  2、pear
  3、banana
  4、cherry"
#(2)提示用户输入
read -t 10 -p "Pls input a num:" num
main $num

# 说明:后续可以写成一个循环-->while true :5 exit

Demand 3:

summary

case总结:

1、case语句就相当于多分支的if语句。case语句优势是更规范、易读

2、case语句适合变量的值少,且为固定的数字或字符串集合。(start、stop、restart)

3、系统服务启动脚本传参的判断多用case语句

Three common colors echo supplement

(1) solid

echo -e "\033[30m 黑色 \033[0m"
echo -e "\033[31m 红色 \033[0m"
echo -e "\033[32m 绿色 \033[0m"
echo -e "\033[33m 黄色 \033[0m"
echo -e "\033[34m 蓝色 \033[0m"
echo -e "\033[35m 紫色 \033[0m"
echo -e "\033[36m 天蓝色 \033[0m"
echo -e "\033[37m 白色 \033[0m"

(2) blending

echo -e "\033[40;37m 黑底白字 \033[0m"
echo -e "\033[41;37m 红底白字 \033[0m"
echo -e "\033[42;37m 绿底白字 \033[0m"
echo -e "\033[43;37m 黄底白字 \033[0m"
echo -e "\033[44;37m 蓝底白字 \033[0m"
echo -e "\033[45;37m 紫底白字 \033[0m"
echo -e "\033[46;37m 天蓝底白字 \033[0m"
echo -e "\033[47;30m 白底黑字 \033[0m" 

# 背景和字体颜色!

Help Documentation : man console_codes

Good color

Guess you like

Origin blog.csdn.net/wzj_110/article/details/100189781