case语法案例
制作nginx启停脚本
1.条件:
启动服务命令/application/nginx/sbin/nginx 停止服务命令/application/nginx/sbin/nginx -s stop 实现/etc/init.d/nginxd {start|stop|restart},并可chkconfig开机自起
2.思路:
1)nginx启动成功会有一个PID文件,所以根据判断该文件是否存在来确定nginx是开启还是关闭状态 2)通过脚本传入参数start或stop,通过case语句取值判断 3)为了专业,调用系统函数库的action函数 4)对函数及命令允许的返回值进行处理,是脚本看起来更专业、规范 5)通过chkconfig来管理nginx脚本,实现开机自启动
3.脚本
cat /etc/init.d/nginxd
#!/bin/sh
# chkconfig: 2345 40 98
# description: Start/Stop Nginx server
path=/application/nginx/sbin
pid=/application/nginx/logs/nginx.pid
RETVAL=0
. /etc/init.d/functions
start(){
if [ ! -f $pid ];then
$path/nginx
RETVAL=$?
if [ $RETVAL -eq 0 ];then
action "nginx is started" /bin/true
return $RETVAL
else
action "nginx is started" /bin/false
return $RETVAL
fi
else
echo "nginx is running"
return 0
fi
}
stop(){
if [ -f $pid ];then
$path/nginx -s stop
RETVAL=$?
if [ $RETVAL -eq 0 ];then
action "nginx is stopped" /bin/true
return $RETVAL
else
action "nginx is stopped" /bin/false
return $RETVAL
fi
else
echo "nginx is no running"
return $RETVAL
fi
}
case "$1" in
start)
start
RETVAL=$?
;;
stop)
stop
RETVAL=$?
;;
restart)
stop
sleep 1
start
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|reload}"
exit 1
esac
exit $RETVAL
chomod x /etc/init.d/nginxd
- 参考脚本
linux系统内部有很多值得学习的参考的脚本,空了请研究如下脚本
- /etc/init.d/rpcbind
- /etc/init.d/functions
- /etc/rc.d/rc.sysinit
添加删除openvppn用户的脚本
1.实现要求
1) 命令用法:
实现通过传参的方式往/etc/openvpn_authfile.conf里添加用户
USAGE: sh adduser {-add|-del|-search} username
2) 传参要求:
-add 表示添加后面接的用户名
-del 表示删除后面接的用户名
-search 表示查找后面接的用户名
3) 细节要求
如果用户存在则不能添加,不存在则不能删除,查找结果要给用户明确提示
/etc/openvpn_authfile.conf不能被所有外部用户直接删除及修改
2.具体脚本
- cat /server/scripts/b8.sh
#!/bin/bash
. /etc/init.d/functions
FILE_PATH=/etc/openvpn_authfile.conf
[ -f $filepath ] || touch $filepath
usage(){
echo "usage:`basename $0` {-add|-del|-search} username"
}
if [ $UID -ne 0 ]
then
echo "you are not root,must use root"
exit 1
fi
if [ $# -ne 2 ]
then
usage
exit 2
fi
case "$1" in
-add|-a)
shift #位置参数左移,$2替换$1
if grep "^$1$" ${FILE_PATH} >/dev/null 2>&1
then
action $"vpnuser,$1 is exist" /bin/false
exit
else
chattr -i ${FILE_PATH}
/bin/cp ${FILE_PATH} ${FILE_PATH}.$(date %F%T)
echo "$1" >>${FILE_PATH}
[ $? -eq 0 ] && action $"add $1" /bin/true
chattr i ${FILE_PATH}
fi
;;
-d|-del)
shift
if [ `grep "b$1b" ${FILE_PATH}|wc -l` -lt 1 ]
then
action $"vpnuser,$1 is not exist" /bin/false
exit
else
chattr -i ${FILE_PATH}
/bin/cp ${FILE_PATH} ${FILE_PATH}.$(date %F%T)
sed -i "/^${1}$/d" ${FILE_PATH}
[ $? -eq 0 ] && action $"DEL $1" /bin/true
chattr i ${FILE_PATH}
exit
fi
;;
-s|-search)
shift
if [ `grep -w "$1" ${FILE_PATH}|wc -l` -lt 1 ]
then
echo $"vpnuser,$1 is no exist."
exit
else
echo $"vpnuser,$1 is exist."
exit
fi
;;
*)
usege
exit
;;
esac
注意本例中用到的grep三种精确过滤方法 grep -w "oldboy" /file grep "bodlboyb" /file grep "^oldboy$" /file