编程符号网的博客   ITGUEST

使用Shell制作一个服务启动脚本

经常使用脚本启动项目,于是乎整理了一个完整的共享给大伙!!

#!/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

 

posted @ 2021-09-05 16:03  java虾米  阅读(287)  评论(0)    收藏  举报