Linux Java Jar Shell 脚本

2023-12-16 14:27:03

博文目录

文章目录


使用方式

  • ./run.sh start
  • ./run.sh stop
  • ./run.sh restart
  • ./run.sh status
#!/bin/bash

JAVA_CMD="java"
APP_NAME="bid"
JAR_NAME="bid.jar"
PROFILE="develop"

BASE_PATH=`cd $(dirname $0); pwd`
# 应用基础目录下的 env 文件中定义的变量
# source ${BASE_PATH}/env

OPTIONS="-XX:MetaspaceSize=256M"
OPTIONS="${OPTIONS} -jar ${BASE_PATH}/${JAR_NAME}"
OPTIONS="${OPTIONS} --spring.profiles.active=${PROFILE}"

echoRed() { echo $'\e[0;31m'"$1"$'\e[0m'; }
echoCyan() { echo $'\e[0;36m'"$1"$'\e[0m'; }
echoYellow() { echo $'\e[0;33m'"$1"$'\e[0m'; }

[[ -z "$stopWaitTime" ]] && stopWaitTime=10

getPid() {
  pid=`ps ax | grep -i ${JAR_NAME} | grep java | grep -v grep | awk '{print $1}'`
}

start() {
  getPid
  if [ -z ${pid} ] ; then
    doStart
  else
    echoCyan "[${APP_NAME}] 正在运行 ($pid)"
    exit 1
  fi
}

doStart() {
  echoCyan "${JAVA_CMD} ${OPTIONS}"
  # nohup ${JAVA_CMD} ${OPTIONS} > ${BASE_PATH}/start.out/dev/null 2>&1 &
  nohup ${JAVA_CMD} ${OPTIONS} > /dev/null 2>&1 &
  # 等待启动
  startCounter=0 # 记录等待次数
  while [ -z ${pid} ]
  do
    sleep 1
    startCounter=`expr $startCounter + 1`
    echoCyan "[${APP_NAME}] 启动中, ${startCounter}..."
    getPid
    if [ "$startCounter" -ge $stopWaitTime ];then
        pid=""
    fi
  done
  # 输出启动结果
  if [ -z ${pid} ] ; then
       echoRed "[${APP_NAME}] 启动失败"
  else
       echoCyan "[${APP_NAME}] 已启动 ($pid)"
  fi
}

restart() {
  stop && start
}

stop() {
  getPid
  #是否在运行
  if [ -z ${pid} ] ; then
    echoYellow "[${APP_NAME}] 未在运行"
    exit 0;
  fi
  #停止服务
  echoCyan "[${APP_NAME}] 正在运行 (${pid})"
  kill ${pid} #&
  #等待kill没有效果,去掉
  #kpid=$!
  #wait $kpid

  #等待停止
  stopCounter=0
  getPid
  while [ ${pid} ] ; do
    sleep 1
    stopCounter=`expr $stopCounter + 1`
    echoCyan "[${APP_NAME}] 停止中, ${stopCounter} 秒 ..."
    getPid
    if [ "$stopCounter" -ge $stopWaitTime ];then
        echoCyan "[${APP_NAME}] 强制停止 ..."
        kill -9 ${pid}
    fi
  done

  #输出结果
  getPid
  if [ -z ${pid} ] ; then
    echoCyan "[${APP_NAME}] 已停止"
  else
    echoRed "[${APP_NAME}] 停止失败"
  fi
}

status() {
    getPid
    if [ -z ${pid} ] ; then
      echoYellow "[${APP_NAME}] 未在运行"
      exit 0
    else
      echoCyan "[${APP_NAME}] 正在运行 ($pid)"
      exit 0
    fi
}

case "$1" in
    'start')
        start
        ;;
    'stop')
        stop
        ;;
    'restart')
        stop
        start
        ;;
    'status')
        status
        ;;
    *)
        echo "Usage: $0 { start | stop | restart | status }"
        exit 1
        ;;
esac

exit 0

文章来源:https://blog.csdn.net/mrathena/article/details/135031875
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。