#!/bin/bash
# 设置环境变量
export JAVA_HOME=/usr/local/jdk1.8.0_201
export PATH=$PATH:$JAVA_HOME/bin
#输入的jar包名称
jar_name=$1
pid_file="/tmp/${jar_name}.pid"
# jar包的路径
jar_path="/opt/app/${jar_name}.jar"
# 备份的路径
backup_path="/opt/app/backup/${jar_name}-$(date +%Y%m%d%H%M%S).jar"
case "$2" in
start)
if [ -f "$pid_file" ] && kill -0 $(cat "$pid_file") > /dev/null 2>&1; then
echo "Process already running with pid $(cat $pid_file)"
exit 1
fi
cp "$jar_path" "$backup_path"
nohup java -jar $jar_path > /dev/null 2>&1 &
echo $! > "$pid_file"
echo "Started process with pid $(cat $pid_file)"
;;
restart)
if [ -f "$pid_file" ] && kill -0 $(cat "$pid_file") > /dev/null 2>&1; then
echo "Stopping process with pid $(cat $pid_file)"
kill $(cat "$pid_file")
sleep 3
fi
cp "$jar_path" "$backup_path"
echo "Starting process"
nohup java -jar $jar_path > /dev/null 2>&1 &
echo $! > "$pid_file"
echo "Started process with pid $(cat $pid_file)"
;;
stop)
if [ -f "$pid_file" ] && kill -0 $(cat "$pid_file") > /dev/null 2>&1; then
echo "Stopping process with pid $(cat $pid_file)"
kill $(cat "$pid_file")
rm "$pid_file"
echo "Stopped process with pid $(cat $pid_file)"
else
echo "Process not running"
exit 1
fi
;;
*)
echo "Usage: $0 <jar_name> {start|restart|stop}"
exit 1
;;
esac
在这个脚本中,$1 表示传入的第一个参数,即 jar 包的名称,$2 表示传入的第二个参数,即操作类型(start、restart 或 stop)。根据不同的操作类型执行不同的命令:
start:启动进程,如果进程已经在运行,则不执行任何操作;
restart:重启进程,如果进程未运行,则启动进程;
stop:停止进程,如果进程未运行,则不执行任何操作。
如果操作类型不是 start、restart 或 stop,则输出用法并退出