Java - sh 脚本启动 jar 包等服务 - sh 脚本模板 - 适用于任何类似的服务启动

sh 脚本模板

该模板,每次运行一次都会 kill 掉原来的服务,然后重新启动 jar 包服务

#!/bin/bash

# 定义Java进程的名称
APP_NAME=your-app-name.jar

# 定义Java进程的日志文件路径
LOG_PATH=/var/log/your-app-name.log

# 定义备份日志文件的目录
BACKUP_DIR=/var/log/backup

# 定义Java进程的启动参数
JAVA_OPTS="-Xmx1024m -Xms1024m -XX:MaxPermSize=256m"

# 检查Java进程是否存在
PID=$(ps -ef | grep ${APP_NAME} | grep -v grep | awk '{print $2}')
if [[ -n ${PID} ]]; then
  echo "Java process is running, PID is ${PID}. Killing..."
  kill -9 ${PID}
fi

# 检查日志文件是否存在
if [[ -f ${LOG_PATH} ]]; then
  echo "Log file exists. Backing up..."
  if [[ ! -d ${BACKUP_DIR} ]]; then
    mkdir ${BACKUP_DIR}
  fi
  cp ${LOG_PATH} ${BACKUP_DIR}/$(date +%Y%m%d%H%M%S).log
  echo "Log file backed up to ${BACKUP_DIR}."
fi

# 启动Java进程
nohup java ${JAVA_OPTS} -jar ${APP_NAME} > ${LOG_PATH} 2>&1 &

# 检查Java进程是否启动成功
sleep 10
PID=$(ps -ef | grep ${APP_NAME} | grep -v grep | awk '{print $2}')
if [[ -n ${PID} ]]; then
  echo "Java process started successfully, PID is ${PID}."
else
  echo "Failed to start Java process."
fi


参考链接

1. Linux重启Java进程的.sh脚本详解

你可能感兴趣的:(Linux,java,jar,python)