实际工作中开发环境或本地测试有时候需要手动部署jar包,每次启动、关闭、重启很繁琐,使用该脚本可简化测试时jar启动管理

  1. 启动jar包,指定参数-Dxx=nn
    ./jar-admin.sh /tmp/xxxx.jar start -Dxx=nn
  2. 重启jar包,指定参数-Dxx=nn
    ./jar-admin.sh /tmp/xxxx.jar restart -Dxx=nn
  3. 停止jar包
    ./jar-admin.sh /tmp/xxxx.jar stop
  4. 打印jar包启动命令
    ./jar-admin.sh /tmp/xxxx.jar cmd -Dxx=nn
#!/bin/bash
# 注意设置环境变量
# export JAVA_HOME=/root/tools/jdk1.8.0_181
# export JRE_HOME=/$JAVA_HOME/jre
# export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
# export PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin
# =====author:Jamin========
# 1. 启动jar包,指定参数-Dxx=nn
# ./jar-admin.sh xxxx.jar start -Dxx=nn
# 2. 重启jar包,指定参数-Dxx=nn
# ./jar-admin.sh xxxx.jar restart -Dxx=nn
# 3. 停止jar包
# ./jar-admin.sh xxxx.jar stop
# 4. 打印jar包启动命令
# ./jar-admin.sh xxxx.jar cmd -Dxx=nn

#使用说明,用来提示输入参数
usage() {
    echo "Usage: sh jar-admin.sh xxx.jar [start|stop|restart|status|cmd]"
    exit 1
}
LOG_DIR=/tmp/jarlog
APP_NAME=$1
# 支持设置的自定义参数位,需要更多自己加
SB=$2
SC=$3
SD=$4
if [ ! -f "$APP_NAME" ]; then
    echo $APP_NAME ' jar包 not found'
    usage
    exit 1
fi
temp=${APP_NAME##*/}
LOG_FILE=$LOG_DIR/${temp%-1.*}.log
echo "日志文件: ${LOG_FILE}";
if [ ! -d $LOG_DIR ]; then
  mkdir -p $LOG_DIR
fi

#检查程序是否在运行
is_exist(){
  pid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v jar-admin|awk '{print $2}'`
  #echo 'ps -ef|grep '$APP_NAME"|grep -v grep|awk '{print $2}'"
  #如果不存在返回1,存在返回0     
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}
# 获取执行命令方法
cmd(){
    echo "==============START COMMAND==============" $3
    echo "nohup java -jar ${APP_NAME} ${SC} ${SD}  > $LOG_FILE 2>&1 &"
    exit 1
}
#启动方法
start(){
  is_exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} is already running. pid=${pid}"
  else
    nohup java -jar ${APP_NAME} ${SC} ${SD}  > $LOG_FILE 2>&1 &
    sleep 1
    pid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v jar-admin|awk '{print $2}'`
    echo "$(date "+%Y-%m-%d %H:%M:%S") - ${APP_NAME} start ..."
    echo "pid is ${pid}"
    echo "START SUCCESS"
  fi
}


#停止方法
stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -9 $pid
    echo "$(date "+%Y-%m-%d %H:%M:%S") - ${APP_NAME} stop ..."
    echo "STOP SUCCESS"
  else
    echo "${APP_NAME} is not running"
  fi  
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is running. Pid is ${pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}

#重启
restart(){
  stop
  sleep 5
  start
}

#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$2" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  "cmd")
    cmd
    ;;
  *)
    usage
    ;;
esac

标签: shell, echo, grep, jar, NAME, JAVA, admin, APP, JAR

相关文章推荐

添加新评论,含*的栏目为必填