#前言:这篇我们接着写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<<-EOF =============================== 1.banana 2.apple 3.pear 4.cherry =============================== EOF
#执行效果
#如果输入不正确或者不输入的话就打印帮助
[root@shell scripts]# sh menu.sh ############################# 1.banana 2.apple 3.pear 4.cherry ############################# please select a num: please input {1|2|3|4}
#输入选项中的数字,打印相关信息
实践3.开发nginx启动脚本
#主要思路:
#1.主要通过判断nginx的pid文件有无存在,通过返回值查看有没有运行
#2.通过case语句获取参数进行判断
#3.引入系统函数库functions中的action函数
#4.对函数及命令运行的返回值进行处理
#5.设置开机自启动
#附上nginx编译安装过程
#!/bin/bash yum install gcc pcre pcre-devel wget openssl openssl-devel.x86_64 -y mkdir -p /home/demo/tools cd /home/demo/tools/ wget -q http://nginx.org/download/nginx-1.6.3.tar.gz useradd nginx -s /sbin/nologin -M tar xf nginx-1.6.3.tar.gz cd nginx-1.6.3/ ./configure --user=nginx --group=nginx --prefix=/application/nginx --with-http_stub_status_module --with-http_ssl_module make make install ln -s /application/nginx-1.6.3 /application/nginx/ #做软连接 /application/nginx/sbin/nginx -t #检查语法 /application/nginx/sbin/nginx #启动服务详解shell脚本中的case条件语句介绍和使用案例
扫一扫手机访问
