大致框架就是一个case 结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
case
"$1"
in
start) start
;;
stop) stop
;;
restart) stop
start
;;
*) echo "usage:..."
exit 1
esac |
前面在定义start stop 函数
在case中调用就行了。
比如说nginx 的脚本
prog=/usr/local/nginx/sbin/nginx
[ -x $prog ] || exit 0
start(){
$prog
}
stop(){
$prog -s stop
}
当然start 需要再完善一下,比如说检测是否已经有nginx的进程了,pgrep nginx
差不多写完是这样的:
prog=/usr/local/nginx/sbin/nginx #. /etc/rc.d/init.d/functions [ -x $prog ] || exit 99 start(){ pgrep nginx >/dev/null if [ "$?" -eq "0" ] ;then echo "program exist" exit 0 else echo -n "start $prog: " $prog echo "..ok" fi } stop(){ pgrep nginx >/dev/null if [ "$?" -eq "1" ] ;then echo "there is no nginx running." exit 0 else echo "stop $prog: " $prog -s stop echo "..ok" fi } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo "usage: $0 [start|stop|restart]" exit 1 esac
完了和系统的那些脚本对比了一下,发现都用了
. /etc/rc.d/init.d/functions 里面的函数,daemon , killproc 什么的。
还要琢磨一下。写好一个脚本还是不容易的。继续学习中。。
再来一个memcached 的脚本,必须指定监听ip,不然默认0.0.0.0 ,外网也能访问不安全。
prog=/usr/bin/memcached pname=`basename $prog` #. /etc/rc.d/init.d/functions [ -x $prog ] || exit 99 start(){ #check the 11211 port netstat -lntp|grep 11211 >/dev/null if [ "$?" -eq "0" ] ;then echo "error: 11211 is bind ." exit fi #check the process of memcached pgrep $pname>/dev/null if [ "$?" -eq "0" ] ;then echo "error: program exist" exit 0 else echo -n "start $prog: " $prog -u nobody -l 127.0.0.1 -d echo "..ok" fi } stop(){ pgrep $pname>/dev/null if [ "$?" -eq "1" ] ;then echo "there is no $pname running." exit 0 else echo "stop $prog: " pkill $pname echo "..ok" fi } status(){ pgrep $pname if [ "$?" -eq "0" ]; then echo " is running." else echo "$pname is not running"
fi
} case "$1" in start) start ;; stop) stop ;; status) status ;; restart) stop start ;; *) echo "usage: $0 [start|stop|restart]" exit 1 esac