shell脚本中的case条件语句介绍和使用案例 |
您所在的位置:网站首页 › shell中的判断语句 › shell脚本中的case条件语句介绍和使用案例 |
#前言:这篇我们接着写shell的另外一个条件语句case,上篇讲解了if条件语句。case条件语句我们常用于实现系统服务启动脚本等场景,case条件语句也相当于if条件语句多分支结构,多个选择,case看起来更规范和易读
#case条件语句的语法格式 case "变量" in 值1) 指令1... ;; 值2) 指令2... ;; *) 指令3... esac#说明:当变量的值等于1时,那么就会相应的执行指令1的相关命令输出,值等于2时就执行指令2的命令,以此类推,如果都不符合的话,则执行*后面的指令,要注意内容的缩进距离
#简单记忆 case "找工作条件" in 给的钱多) 给你工作... ;; 给股份) 给你工作... ;; 有发展前景) 可以试试... ;; *) bye bye !! esac
#实践使用 实践1.根据用户的输入判断用户输入的是哪个数字,执行相应动作#如果用户输入的是1-9的任意一个数字,则输出对应输入的数字,如果是别的字符,则提示输出不正确并退出程序 [root@shell scripts]# cat num.sh #!/bin/bash #create by guoke #function number input read -p "please input a number:" num #打印信息提示用户输入,输入信息赋值给num变量 case "$num" in 1) echo "The num you input is 1" ;; [2-5]) echo "The num you input is 2-5" ;; [6-9]) echo "The num you input is 6-9" ;; *) echo "please input number[1-9] int" exit; esac#说明:使用read读取用户输入的数据,然后使用case条件语句进行判断,根据用户输入的值执行相关的操作
#执行效果 [root@shell scripts]# sh num.sh please input a number:1 The num you input is 1 [root@shell scripts]# sh num.sh please input a number:3 The num you input is 2-5 [root@shell scripts]# sh num.sh please input a number:4 The num you input is 2-5 [root@shell scripts]# sh num.sh please input a number:8 The num you input is 6-9 [root@shell scripts]# sh num.sh please input a number:a please input number[1-9] int实践2.打印一个如下的水果菜单 (1) banana (2) apple (3) orange (4) cherry #脚本编写 [root@shell scripts]# cat menu.sh #!/bin/bash #create by guoke #function print menu RED_COLOR='\E[1;31m' GREEN_COLOR='\E[1;32m' YELLOW_COLOR='\E[1;33m' BLUE_COLOR='\E[1;34m' RES='\E[0m' echo ' #使用echo打印菜单 ############################# 1.banana 2.apple 3.pear 4.cherry ############################# ' read -p "please select a num:" num case "$num" in 1) echo -e "${YELLOW_COLOR} banana ${RES}" ;; 2) echo -e "${RED_COLOR} apple ${RES}" ;; 3) echo -e "${GREEN_COLOR} pear ${RES}" ;; 4) echo -e "${BLUE_COLOR} cherry ${RES}" ;; *) echo "please input {1|2|3|4}" esac#说明:定义颜色,使用read读取用户输入的数据,然后使用case条件语句进行判断,根据用户输入的值执行相关的操作,给用户输入的水果添加颜色
#扩展:输出菜单的另外种方式 cat |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |