Spring Boot 自动启动Shell脚本

#!/usr/bin/bash
# 获取执行路径
APP_DIR=$( cd $( dirname $0 );pwd );
# 查找jar包文件
BOOT_JAR_PATH=$(find ${APP_DIR} -type f -name *.jar);
BOOT_JAR=$(basename $BOOT_JAR_PATH);
# 获取应用名(文件名)
APP_NAME=$(echo ${BOOT_JAR} | sed 's/.jar//1');
LOG_DIR=${APP_DIR}/logs;
LOG_CONSOLE=${LOG_DIR}/${APP_NAME}-console.log;
#
JAVA_OPTS='-Xms512M -Xmx512M';
CMD_ARGS=''
# 改色
echo -e "\033[44m\033[37m"
echo "======================================================";
echo "                                                      ";
echo "启动路径:${APP_DIR}";
echo "引导JAR包:${BOOT_JAR_PATH}";
echo "应用名称:${APP_NAME}";
echo "日志目录:${LOG_DIR}";
echo "                                                      ";
echo -e "======================================================\033[40m\033[37m";
echo "                                                      ";
#-----------------------------

mkdir -p $LOG_DIR;

# ----------------------------

process_pid(){
 local PID=$(ps -ef |grep ${BOOT_JAR_PATH} | grep -v grep| awk '{print $2}');
 if [ -z "${PID}" ]; then
   echo 0;
 else
   echo $PID;
 fi
}

# ------------------------------

run(){
  local PID=$(process_pid);
  if ! [ 0 -eq ${PID} ]; then
    echo "服务已启动:${BOOT_JAR},进程:$PID";
    echo
    return;    
  fi;
  echo "命令行调试:${BOOT_JAR_PATH}";
  java ${JAVA_OPTS} -jar ${JAVA_OPTS} -jar ${BOOT_JAR_PATH} ${CMD_ARGS};
}

# -----------------------------

status(){
  echo "开始检测服务:${BOOT_JAR_PATH}";
  local PID=$(process_pid);
  if [ 0 -eq ${PID} ]; then
    echo "服务未启动:${BOOT_JAR}";
    echo;
    return;
  else
    echo "服务已启动:${BOOT_JAR},进程:$PID";
    echo;
    return;
 fi
}

# ------------------------------

start(){ 
  local PID=$(process_pid);
  if ! [ 0 -eq ${PID} ]; then
    echo "服务已启动:${BOOT_JAR},进程:$PID";
    echo
    return;    
  fi;
  echo "准备启动服务:${BOOT_JAR_PATH}";
  nohup java -server ${JAVA_OPTS} -jar ${BOOT_JAR_PATH} ${CMD_ARGS} > ${LOG_CONSOLE} 2>&1 &
  while :
  do
    # 检查进程是否存在
    PID=$(process_pid);
    if ! [ 0 -eq ${PID} ]; then
        echo "服务已启动:${BOOT_JAR_PATH},进程ID:${PID}"
        echo
        break
    fi
    # 等待一段时间后继续检查
    sleep 1
  done
}

# ------------------------------

stop(){
  local PID=$(process_pid);
  if [ 0 -eq ${PID} ]; then
    echo "服务未启动";
    echo;
    return;    
  fi;
  echo "准备停止服务:${BOOT_JAR_PATH},进程ID:${PID}";
  kill -15 ${PID};
  while :
    do
      # 检查进程是否存在
      KPID=$(process_pid);
      if [ 0 -eq ${KPID} ]; then
          echo "服务已停止:${BOOT_JAR_PATH},进程ID:${PID}";
          echo;
          break
      fi
      # 等待一段时间后继续检查
      sleep 1
    done
}

# ------------------------------

restart(){
  stop
  start
}

# ==========================


case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "run")
    run
    ;;
   "restart")
    restart
    ;;
  *)
    echo "正确用法: $0 [run|start|stop|restart|status]"
    exit 1
esac

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享