|
1.case结构条件语句语法
case语句实际上就是规范的多分支if语句
case “字符串变量”in
值1)指令1…
;;
值2)指令2…
;;
*)指令3…
esac
中文编程语法:
case “找女朋友条件”in
有房)嫁给你…
;;
你爸是李刚)嫁给你…
;;
努力吃苦)可以考虑先谈朋友…
;;
*)good bye!!!
esac
2.简单case脚本
输入1、2、3分别输出对应的值
[root@shellbiancheng jiaobenlianxi]# cat case01.sh
#!/bin/bash
usage() {
echo "USAGE:$0 {1|2|3}" contents
exit 1
}
num() {
case "$1" in
1)echo "1"
;;
2)echo "2"
;;
3)echo "3"
;;
*)usage
esac
}
main() {
if [ $# -ne 1 ];then
usage
fi
num $1
}
main $*
3.执行脚本打印一个水果菜单如下:
a.apple
b.pear
c.banana
d.cherry
当用户选择水果的时候,打印告诉它选择的水果是什么并给选择的水果加上颜色。要求case语句实现。
[root@shellbiancheng jiaobenlianxi]# cat menufruit.sh
#!/bin/bash
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
SHAN='\E[31;5m' 提示闪烁功能结合 echo –e 使用
RES='\E[0m'
menu(){
cat ../init.d/rpcgssd
[root@shellbiancheng logs]# ll /etc/rc.d/rc3.d/ |grep S20
脚本代码如下:
[root@shellbiancheng jiaobenlianxi]# cat nginx.sh
#!/bin/bash
# chkconfig: 2345 20 16
# description: nginx is a http server
#Date: 2018-04-07
#Author: Create by linzhongniao
#Mail: xxxxxxxxxx@163.com
#Function:This scripts function is Nginx startup script.
#Version: 1.1
if [ -f /etc/init.d/functions ];then
. /etc/init.d/functions
fi
pidfile=/usr/local/nginx/logs/nginx.pid
SHAN='\E[31;5m'
RES='\E[0m'
nginx=/usr/local/nginx/sbin/nginx
RETVAL=0
linzhongniao() {
RETVAL=$?
if [ $RETVAL -eq 0 ];then
action "Nginx is $1" /bin/true
else
action "Nginx is $1" /bin/true
fi
}
start() {
if [ -f $pidfile ];then
echo -e ${SHAN}"nginx is running"${RES}
else
$nginx
linzhongniao started
fi
return $RETVAL
}
stop() {
if [ ! -f $pidfile ];then
echo -e ${SHAN}"nginx is stopped"${RES}
else
$nginx -s stop
linzhongniao stopped
fi
return $RETVAL
}
restart() {
printf "Restarting Nginx ...\n"
stop
sleep 2
start
}
reload() {
if [ ! -f $pidfile ];then
echo -e ${SHAN}"Can't open $pidfile,no such file or directory"${RES}
else
$nginx -s>
linzhongniao> fi
return $RETVAL
}
usage() {
echo -e ${SHAN}"USAGE:$0 {start|stop|restart|reload}"${RES}
}
main() {
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
reload)
reload
;;
*)usage
exit $RETVAL
esac
}
main $1
exit $RETVAL
最后我们把它加载到chkconfig里面,完成nginx服务开机自启动
[root@shellbiancheng init.d]# chkconfig nginx on
[root@shellbiancheng init.d]# chkconfig --list nginx
nginx 0:关闭 1:关闭 2:启用 3:启用 4:启用 5:启用 6:关闭
关闭开机自启动
[root@shellbiancheng init.d]# chkconfig nginx off
[root@shellbiancheng init.d]# chkconfig --list nginx
nginx 0:关闭 1:关闭 2:关闭 3:关闭 4:关闭 5:关闭 6:关闭
5.case语句小结
(1)case语句相当于多分支的if语句。case语句优势更规范、易读。
(2)case语句适合变量值少,并且固定的数字或字符串的集合。(1,2,3)或(start,stop,restart)。
(3)系统服务启动脚本传参多使用case语句,参考/etc/init.d/rsyslog的启动脚本。
(4)所有case语句都可以使用if实现,但是case语句更规范清晰一些。
(5)case语句一般适合于服务的启动脚本。
(6)case的变量的值如果已知固定的start/restart/stop的元素比较适合。
语句小结:
(1)case主要是写启动脚本,范围较窄。
(2)if取值判断、比较、应用广泛。
6.学习系统脚本
多向系统脚本学习
/etc/init.d/functions
函数库functions详解:http://www.cnblogs.com/image-eye/archive/2011/10/26/2220405.html
/etc/rc.d/rc.sysinit
/etc/init.d/rpcbind
/etc/init.d/nfs
/etc/init.d/httpd
|
|
|