这两周开始学习shell编程的一些基础知识,在哔哩哔哩上跟着老男孩教育白树明老师的讲解进行学习,下边是我按照老师的脚本进行的模仿练习,原文链接:http://book.ayitula.com/shelljiao-ben/han-shu/job.html
以下代码仅供参考,大家一起来学习shell脚本啊!
#!/bin/bash
#varibles
nginx_install_doc=/application/nginx
proc=nginx
nginxd=$nginx_install_doc/sbin/nginx
pid_file=$nginx_install_doc/logs/nginx.pid
#source function library 调用函数库
if [ -f /etc/init.d/functions ];then
. /etc/init.d/functions
else
echo "not found file /etc/init.d/functions"
exit
fi
#判断pid进程号,以及对应的进程数量是多少
if [ -f $pid_file ];then
nginx_process_id=`cat $pid_file`
nginx_process_num=`ps -aux|grep $nginx_process_id|grep -v "grep"|wc -l`
#除去grep那一条的进程,其余的进程数量
fi
#function
start () {
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then #如果pid文件存在并且进程数量大于等于1,则nginx已经启动,不需要再启动
echo "nginx running..."
else
if [ -f $pid_file ]&& [ $nginx_process_num -lt 1 ];then #如果pid文件存在,但是进程数量小于1,则没有nginx这个进程,需要删除pid文件,并启动nginx
rm -f $pid_file
echo "nginx start `daemon $nginxd`" #第一种启动的写法
#action "nginx start" daemon $nginxd #第二种启动的写法
fi
echo "nginx start `daemon $nginxd`"
fi
}
stop () {
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
action "nginx stop" killall -s QUIT $proc #QUIT是结束进程时会等待该进程的请求执行完,stop是不管是否有请求,直接关闭该进程。
rm -f $pid_file
else
action "nginx stop" killall -s QUIT $proc 2>/dev/null
fi
}
restart (){
stop
sleep 1
start
}
reload (){
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
action "nginx reload " killall -s HUP $proc #如果想要更改配置而不需停止并重新启动服务
else
action "nginx reload " killall -s HUP $proc 2>/dev/null
fi
}
status (){
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
echo "nginx is running..."
else
echo "nginx is stop..."
fi
}
#callable
case $1 in
start) start;;
stop) stop;;
restart) restart;;
reload) reload;;
status) status;;
*) echo "usage: $0 start|stop|restart|reload|status"
esac