#!/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
In diesem Skript stellt $1 den ersten übergebenen Parameter dar, der den Namen des JAR-Pakets darstellt, und $2 stellt den zweiten übergebenen Parameter dar, der den Operationstyp (Start, Neustart oder Stopp) darstellt. Führen Sie je nach Operationstyp unterschiedliche Befehle aus:
Start: Prozess starten, nichts tun, wenn der Prozess bereits läuft;
Neustart: Prozess neu starten, Prozess starten, wenn er nicht läuft;
Stopp: Prozess stoppen, nichts tun, wenn der Prozess nicht läuft.
Wenn der Aktionstyp nicht „Starten“, „Neu starten“ oder „Stoppen“ lautet, drucken Sie die Verwendung aus und beenden Sie den Vorgang