shell脚本中的case条件语句介绍和使用案例

2023-05-26,,

#前言:这篇我们接着写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
)
echo "The num you input is 1"
;;
[-])
  echo "The num you input is 2-5"
;;
[-])
  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:
The num you input is
[root@shell scripts]# sh num.sh
please input a number:
The num you input is -
[root@shell scripts]# sh num.sh
please input a number:
The num you input is -
[root@shell scripts]# sh num.sh
please input a number:
The num you input is -
[root@shell scripts]# sh num.sh
please input a number:a
please input number[-] 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打印菜单
#############################
.banana
.apple
.pear
.cherry
#############################
' read -p "please select a num:" num case "$num" in
)
  echo -e "${YELLOW_COLOR} banana ${RES}"
;;
)
  echo -e "${RED_COLOR} apple ${RES}"
;;
)
  echo -e "${GREEN_COLOR} pear ${RES}"
;;
)
  echo -e "${BLUE_COLOR} cherry ${RES}"
;;
*)
  echo "please input {1|2|3|4}"
esac

#说明:定义颜色,使用read读取用户输入的数据,然后使用case条件语句进行判断,根据用户输入的值执行相关的操作,给用户输入的水果添加颜色

#扩展:输出菜单的另外种方式

cat<<-EOF
===============================
.banana
.apple
.pear
.cherry
===============================
EOF

#执行效果

#如果输入不正确或者不输入的话就打印帮助

[root@shell scripts]# sh menu.sh 

#############################
.banana
.apple
.pear
.cherry
############################# please select a num:
please input {|||}

#输入选项中的数字,打印相关信息

实践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..tar.gz
cd nginx-1.6./
./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. /application/nginx/ #做软连接
/application/nginx/sbin/nginx -t #检查语法
/application/nginx/sbin/nginx #启动服务

#脚本编写

[root@shell init.d]# chmod +x /etc/init.d/nginxd
[root@shell init.d]# cat nginxd
#!/bin/bash
#chkconfig: 2345 40 98 #设定2345级别,开机第40位启动脚本,关机第98位关闭脚本 #create by guoke
#email:@qq.com
#function nginx start scripts [ -f /etc/init.d/functions ] && source /etc/init.d/functions #引入系统函数库 PIDFILE=/application/nginx/logs/nginx.pid #定义PID文件路径
NGINX=/application/nginx/sbin/nginx #定义启动命令路径 value(){ #定义返回值函数
RETVAL=$?
if [ $RETVAL -eq ];then
  action "Nginx is $1" /bin/true
else
  action "Nginx is $1" /bin/true
fi
} start(){ #定义启动函数
if [ -f $PIDFILE ];then #判断PIDFILE存不存在,存在就打印运行,否则就启动
  echo "Nginx is running"
else
  $NGINX
  value start #调用返回值函数
fi
} stop(){ #定义停止函数
if [ ! -f $PIDFILE ];then #也是通过判断PID文件是否存在然后进行相关操作
  echo "Nginx not running"
else
  $NGINX -s stop
  value stop
fi
} reload(){ #定义重启函数
if [ ! -f $PIDFILE ];then
  echo "not open $PIDFILE no such directory"
else
  $nginx -s reload
  value reload
fi
} case "$1" in #使用case接收脚本传参的字符串
start) #如果第一个参数为start,调用start函数
  start
;;
stop)  #如果第一个参数为stop,调用stop函数
  stop
;;
reload)
  stop
  sleep
  start
;;
*)
  echo "USAGE:$0 {stop|start|reload}"
  exit
esac

#执行效果

[root@shell init.d]# sh nginx stop
Nginx is stop [ OK ]
[root@shell init.d]# sh nginx start
Nginx is start [ OK ]
[root@shell init.d]# sh nginx reload
Nginx is stop [ OK ]
Nginx is start [ OK ]

实践4.开发跳板机

#要求用户登录到跳板机后只能执行管理员给定的选项动作,不能中断脚本而到跳板机服务器上执行任何系统命令

#思路

.首先做好ssh key验证登录
.实现远程连接菜单选择脚本
.利用Linux信号防止用户在跳板机上操作
.用户登录后就调用脚本

#操作过程

3.1.做ssh免密钥登录,发送到各个主机,如果机器多的话可以使用脚本进行循环发送

[demo@shell ~]$ ssh-keygen  -t dsa -P "" -f ~/.ssh/id_dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/demo/.ssh/id_dsa):
Created directory '/home/demo/.ssh'.
Your identification has been saved in /home/demo/.ssh/id_dsa.
Your public key has been saved in /home/demo/.ssh/id_dsa.pub.
The key fingerprint is:
SHA256:BTFfcC2hMKBzuZeUYylC3qgza7z4X6j3RBlwq8Beoak demo@shell
The key's randomart image is:
+---[DSA ]----+
| + o.*...+o |
| . = B o O +. . |
| = B B * + . |
| o + = B + |
|E = . + S |
| . + o . |
| + . o |
| o o.o |
|..+o... |
+----[SHA256]-----+
#命令说明:一键生成密钥,不用按回车。-t:指定要创建的密钥类型,-P:提供旧密码,空表示不需要密码,-f:指定位置

#将公钥拷贝到其他服务器的demo用户
[demo@shell ~]$ ssh-copy-id -i .ssh/id_dsa.pub "demo@192.168.86.129"
[demo@shell ~]$ ssh-copy-id -i .ssh/id_dsa.pub "demo@192.168.86.130"
[demo@shell ~]$ ssh-copy-id -i .ssh/id_dsa.pub "demo@192.168.86.131"

#3.2.编写脚本

[root@shell scripts]# cat tiaobanji.sh
#!/bin/bash trapper(){ #定义屏蔽信号函数
trap '' INT QUIT TSTP TERM HUB
} menu(){ #定义菜单列表函数
cat<<-EOF #加-后面的EOF就可以不用顶格
==============Host List==============
) 192.168.86.129
) 192.168.86.130
) 192.168.86.131
) 192.168.86.132
) exit
=====================================
EOF
} USER=demo host(){ #定义主机列表函数
case "$1" in
)
ssh $USER@192.168.86.129
;;
)
ssh $USER@192.168.86.130
;;
)
ssh $USER@192.168.86.131
;;
)
ssh $USER@192.168.86.132
;;
)
exit
esac
} main(){ #定义主函数
while : #while循环,一直循环
do
trapper #调用trapper函数
clear #清屏
menu #调用菜单函数
read -p "please select a num:" num #获取用户输入
host $num #调用主机列表函数和传入的参数,进行远程登录
done
}
main #调用主函数

#3.3.编写脚本进行判断,判断是否是root用户登录,如果不是root用户就执行脚本,弹出跳板机界面

[root@shell ~]# cd /etc/profile.d/
[root@shell profile.d]# cat jump.sh
#!/bin/bash [ $UID -ne ] && . /scripts/tiaobanji.sh

#3.4.测试

#登录demo普通用户输入密码的时候就会直接跳到选项卡页面了

#选项卡页面

==============Host List==============
) 192.168.86.129
) 192.168.86.130
) 192.168.86.131
) 192.168.86.132
) exit
=====================================
please select a num:1 #进行选择
Last login: Tue Mar :: from 192.168.86.128
[demo@mysql ~]$

#3.5.提示:跳板机的安全

.禁止跳板机可以从外网IP进行登录,只能从内网IP登录
.其他服务器也限制只能内网IP登录,同时禁止root登录,做完ssh key认证,将密码登录禁止,通过免密码登录到其他服务器

#总结:if条件语句主要用于取值判断、比较,应用比较广,case条件语句主要是写服务的启动脚本,各有各的优势。好了,shell脚本的条件语句就讲解到这里了,接下来会继续写shell脚本的循环(包括for,while等),如果写的不好的地方还望指出,多多交流提高,下次再会。。。

shell脚本中的case条件语句介绍和使用案例的相关教程结束。

《shell脚本中的case条件语句介绍和使用案例.doc》

下载本文的Word格式文档,以方便收藏与打印。