一、主要shell命令
1、daemon+运行路径
2、killproc+运行路径
3、pidofproc+运行路径
二、具体代码#!/bin/bash
#chkconfig: - 50 60 在脚本前加个chkconfig参数后面跟两个数字,都是1-100以内的就行
#source /etc/init.d/functions 引入函数类库
. /etc/init.d/functions
#引入nginx的启动路径
exec= /usr/local/nginx/sbin/nginx
#定义启动函数
function start(){
pidofproc $exec > /dev/null #这样就可以避免直接输出端口
[ $? -eq 0 ] $$ echo 'nginx is already running!' && exit
daemon $exec
[ $? -eq 0 ] && echo 'nginx start success'
}
#定义关闭
function stop(){
killproc $exec
[ $? -eq 0 ] && echo 'nginx stop success'
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "USAGE:nginx {start|stop|restart}"
;;
esac
#写完后保存退出,记得chmod+x下,加个可执行权限,防止不能被执行
小贴士:输出带颜色的字体
到这里,现在只要保存退出,然后再chomod +x 脚本名
然后到脚本所在目录,运行 ./脚本.sh start就可以启动nginx程序了;
其他的如php、apache同上,我们只需要拷贝一份nginx的shell脚本改下运行目录和提示就可以了;
但是有个问题,我们不可能每次启动都要进入脚本所在目录再启动程序把?所以下面我们再把脚本文件放到全局变量里,这样就可以直接启动程序了,可以这样操作;cp nginx.sh php-fpm.sh
cp nginx.sh httpd.sh
使用vim进入后改下路径和提示,然后再复制到全局
cp nginx.sh /etc/init.d/nginx
cp php-fpm.sh /etc/init.d/php-fpm
cp httpd.sh /etc/init.d/httpd
启动就变为
/etc/init.d/nginx start|stop|restart
/etc/init.d/httpd start|stop|restart
/etc/init.d/php-fpm start|stop|restart
然后用netstat -nltp查看运行的端口
ok,到这里我们只是满足了自己一键启动各个程序,但是能不能做到开机自启动这些程序呢?
三、实现开机自启查看系统启动的程序
chkconfig --list 只看345就行,如果全为on则启动否则无
查看开机启动的程序,不是系统自带的
查看系统自带的开机启动程序systemctl list -unit-files
上图是以防护墙为例,后面的参数enabled代表开机自启,disabled代表不是自启
如防火墙,systemctl disable firewalld就是设置开机不自启动
那么设置非系统程序开机自启怎么做呢?
nginx.sh
chkconfig --add nginx
然后再chconfig nginx on
这样设置好后,关机再启动就可以看到nginx已经启动了,
同理httpd和php