课时9 使用case分支
一、case语句结构
语法格式:
case 变量值
in
模式1)
命令序列1
;;
模式2)
命令序列2
;;
......
*)
默认命令序列
esac
二、基本用法示范
示例1:识别用户击键类
[
root@localhost ~]# cat hitkey.sh
#!/bin/bash
read -p "请输入一个字符,并按Enter键确认:" KEY
case "$KEY" in
[a-z] | [A-Z])
echo "您输入的是 字母"
;;
请输入一个字符,并按Enter键确认:h
您输入的是 字母
三、案例实战
案例实战一:编写服务脚本 sleepd
1、能够响应start、stop控制参数
2、将服务交给chkconfig进行处理
步骤一:在脚本开头设置chkconfig参数
步骤二:添加为系统服务
[
root@localhost ~]# cat /etc/init.d/sleepd
#!/bin/bash
# chkconfig - 90 10
# description Deamon script for sleepd Server
case "$1" in
start)
sleep 3600 &
;;
stop)
pkill -x "sleep"
;;
*)
echo "用法:$0 [ start | stop ]"
;;
esac
[
root@localhost ~]#
/etc/init.d/sleepd start
[
root@localhost ~]# pgrep -lx "sleep"
[
root@localhost ~]#
pgrep -lx "sleep"
用法:
/etc/init.d/
sleepd
[ start | stop ]
[
root@localhost ~]# chkconfig --add sleepd
[
root@localhost ~]#