经常使用脚本启动项目,故此完善脚本记录一下,欢迎小白抱团!
#!/bin/bash
if [ -n "$2" ];
then
echo $addr
else
addr="0.0.0.0:9000"
fi;
function status() {
keyword=$1;
pid=$(ps -ef | grep ${keyword} | awk 'NR==1{print $2}');
child=$(ps -ef | grep ${keyword} | awk 'NR==2{print $3}');
if [[ -n "$pid" ]] && [[ -n "$child" ]] && [[ "$pid" = "$child" ]];
then
echo "the status of server:$keyword is started!";
return 1;
else
echo "the status of server:$keyword is stopped";
return 0;
fi;
}
function start(){
keyword=$1;
index=0
# 失败重启次数
times=10
until [ ! $index -lt $times ]
do
status $keyword;
if [ "$?" = 0 ];
then
echo "[server:$keyword] is starting...";
if [ "$keyword" = "celery" ];
then
nohup python3 manage.py celery -A kw.celery_app:app worker -B -l info > celery.log 2>&1 &
# python manage.py celery -A kw.celery_app:app worker -B -l info -D;
else
gunicorn -w 4 kw.wsgi:application -b ${addr} --reload -D;
fi
fi;
status $keyword;
if [ "$?" != 0 ];
then
echo "[server:$keyword] is started.";
break
else
sleep 10
index=`expr $index + 1`
fi;
done
};
function stop(){
keyword=$1;
status $keyword;
if [ "$?" = 1 ];
then
echo "[server:$keyword] is stopping...";
pid=$(ps -ef | grep ${keyword} | awk 'NR==1{print $2}')
kill ${pid}
echo "[server:$keyword] is stopped";
fi;
};
action=$1
case $action in
start)
start $addr;
start "celery";
;;
stop)
stop $addr;
stop "celery";
;;
restart)
stop $addr;
stop "celery";
start $addr;
start "celery";
;;
status)
status $addr;
status "celery";
;;
*) echo "$0 {start|stop|restart|status}"
exit 4
;;
esac