1 start () {
 2 
 3       echo "Apache start ......        [OK]"
 4       #return 0   可以写一个返回值,比如执行成功返回 0 
 5 }
 6 
 7 stop () {
 8 
 9       echo "Apache stop ......        [Fail]"
10 }
11 
12 start    #调用函数 直接写函数名即可
13 stop

 

实战 nginx 启动管理脚本

 1 #!/usr/bin/env bash
 2 
 3 nginx_dir=/usr/local/nginx
 4 nginxd=$nginx_dir/sbin/nginx
 5 pid_file=$nginx_dir/logs/nginx.pid
 6 proc=nginx
 7 
 8 if [ -e $pid_file ];then
 9 
10     nginx_process_id=`cat $pid_file`
11     nginx_process_num=`ps aux | grep $nginx_process_id | grep -v "grep" | wc -l`
12 fi
13 start(){
14 
15 if [ ! -e /etc/init.d/network ];then
16 
17         echo' /etc/init.d/network doesn`t exist'
18         exit
19 fi
20 . /etc/init.d/functions
21 
22 if [ -e $pid_file ] && [ $nginx_process_num -ge 1 ];then
23     echo "nginx running..."
24 else
25    if [ -e $pid_file ] && [ $nginx_process_num -lt 1 ];then
26         rm -f $pid_file
27        echo " nginx start  ` daemon $nginxad` "
28        #action "nginx start " $nginxd    另外一种写法 对应27行
29    fi
30 echo " nginx start  ` daemon $nginxd` "
31 
32 fi
33 
34 }
35 stop(){
36 
37 if [ -e $pid_file ] && [ $nginx_process_num -ge 1 ];then
38 
39         echo "  nginx stop `killall -s QUIT $proc`"
40 else
41         echo 'nginx stop error'
42 fi
43 }
44 
45 restart(){
46   stop
47   sleep 3
48   start
49 }
50 
51 
52 reload(){
53 
54 if [ -e $pid_file ] && [ $nginx_process_num -ge 1 ];then
55    echo "nginx reload `killall -s HUP $proc`"
56 else
57    echo 'nginx reload failed'
58 
59 fi
60 }
61 status(){
62 if [ -e $pid_file ] && [ $nginx_process_num -ge 1 ];then
63 
64   echo 'nginx running'
65 else
66   echo 'nginx stop'
67 fi
68 
69 }
70 
71 case $1 in
72 start) start;;
73 stop) stop;;
74 restart) restart;;
75 reload) reload;;
76 status) status;;
77 *) echo "USAGE: $0 start|stop|restart|reload|status" ;;
78 esac

 

 

然后将脚本复制到 /etc/init.d/中并命名为nginxd

再修改权限chmod 755 /etc/init.d/nginxd

然后就可以通过service来个控制了

service nginxd status
nginx running

 

posted on 2020-02-12 22:25  wilson'blog  阅读(198)  评论(0)    收藏  举报