如何快速写个启动脚本,主要通过如下几部

1,逻辑捋顺

  • 可以在txt文件中,已伪代码的方式,形成体系,罗列顺序,然后在一点点补充代码

  • 通过PID 进程文件,判断程序是否运行

  • 设置3个模块(开启,关闭,重新加载)

  • 然后在用case语句 去调用这个3个模块 实现启动脚本功能

  • restart看进程号变化,reload看配置文件是否生效

2,脚本主体内容

[root@DB02]# cat /etc/init.d/nginx
#!/bin/bash
# chkconfig: 2345 32 62  #按照开机启动模板设定,32序列号 62系统等级
# description: Activates/Deactivates all network interfaces configured to \
 
[ -f /etc/init.d/functions ] &&  . /etc/init.d/functions  #引用系统函数库
nginx=/application/nginx/sbin/nginx
Pidfile=/application/nginx/logs/nginx.pid
oldboy(){
    RETVAL=$?
    if [ $RETVAL -eq 0 ];then
      action "Nginx is $1" /bin/true
    else
      action "Nginx is $1" /bin/false
    fi
}
##no.1 定义启动模块
Start(){
  if [ -f $Pidfile ];then
    echo "Nginx is running"
   else
    $nginx
    oldboy started
  fi   
  return $RETVAL
}
##no.2 定义关闭模块
Stop(){
  if [ ! -f $Pidfile ];then
    echo "nginx in not running"
    else
    $nginx -s stop
    oldboy stoped
  fi
}
##no.3 定义重新加载模块
Reload(){
  if [ ! -f $Pidfile ];then
    echo "Cat't open $Pidfile ,no such file or directory"
  else
    $nginx -s reload
    oldboy reloaed 
  fi
}
 
case "$1" in
    start)
    Start
;;
    stop)
    Stop
;;
    reload)
    Reload
;;
    restart)
    Stop
    sleep 2
    Start
;;
    *)
    echo "Usage: sh $0 {start|stop|reload|restart} "   
    exit 1
esac
exit   $RETVAL

3,把脚本放到/etc/init.d/ 下

 3.1  查看服务自启动列表

[root@DB02 init.d]# chkconfig --list|grep nginx
[root@DB02 init.d]# chkconfig --list|grep mysql
mysqld         0:关闭1:关闭2:启用3:启用4:启用5:启用6:关闭

 3.2 把脚本写入到/etc/init.d

[root@DB02 init.d]# cd /etc/init.d/
[root@DB02 init.d]# vi nginx   #内容见上面脚本

  3.3 授权脚本 x执行权限

[root@DB02 init.d]# chmod +x nginx 
[root@DB02 init.d]# ll nginx 
-rwxr-xr-x 1 root root 1177 9月  26 15:45 nginx


4,添加开机自启动

[root@DB02 init.d]# chkconfig nginx on
service nginx does not support chkconfig   ##报错,没有把nginx文件,添加到开机自启动里面
[root@DB02 rc3.d]# chkconfig --list|grep nginx
nginx          	0:关闭	1:关闭	2:启用	3:启用	4:启用	5:启用	6:关闭

4.1测试

[root@DB02 rc3.d]# /etc/init.d/nginx start
Nginx is running

另外一种,开机自启动方法,可以把启动内容放到 /etc/rc.local文件中,主要要使用绝对路径


wKioL1nKCdrgHxKuAADIJXOP2sg114.jpg