#!/bin/bash
### BEGIN INIT INFO
# Provides: myprogram
# Required-Start: $local_fs $network $remote_fs
# Required-Stop: $local_fs $network $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: My program description
# Description: My program description
### END INIT INFO
# jar 程序的位置
JAR_FILE=/path/to/myprogram.jar
# Java 命令的路径,可以使用 `which java` 命令获取
JAVA_CMD=/usr/bin/java
# Java 虚拟机的参数
JAVA_OPTS="-Xms256m -Xmx512m"
# log 日志的位置
LOG_FILE=/var/log/myprogram.log
# PID 文件的位置
PID_FILE=/var/run/myprogram.pid
# 检查 jar 文件是否存在
if [ ! -f "$JAR_FILE" ]; then
echo "Jar file not found: $JAR_FILE"
exit 1
fi
# 检查 Java 命令是否存在
if [ ! -f "$JAVA_CMD" ]; then
echo "Java command not found: $JAVA_CMD"
exit 1
fi
# 检查 log 文件是否存在
if [ ! -f "$LOG_FILE" ]; then
touch "$LOG_FILE"
fi
# 检查 PID 文件是否存在
if [ ! -f "$PID_FILE" ]; then
touch "$PID_FILE"
fi
function start() {
# 检查程序是否已经在运行中
pid=$(cat "$PID_FILE" 2>/dev/null)
if [ ! -z "$pid" ]; then
if ps -p "$pid" > /dev/null; then
echo "Program is already running with PID $pid"
return 1
else
echo "Stale PID file found: $PID_FILE"
rm "$PID_FILE"
fi
fi
# 启动程序
nohup $JAVA_CMD $JAVA_OPTS -jar "$JAR_FILE" > "$LOG_FILE" 2>&1 &
pid=$!
echo "$pid" > "$PID_FILE"
echo "Program started with PID $pid"
return 0
}
function stop() {
# 检查程序是否在运行中
pid=$(cat "$PID_FILE" 2>/dev/null)
if [ ! -z "$pid" ]; then
if ps -p "$pid" > /dev/null; then
# 停止程序
kill "$pid"
rm "$PID_FILE"
echo "Program stopped with PID $pid"
return 0
else
echo "Stale PID file found: $PID_FILE"
rm "$PID_FILE"
fi
fi
echo "Program is not running"
return 1
}
function status() {
pid=$(cat "$PID_FILE" 2>/dev/null)
if [ ! -z "$pid" ]; then
if ps -p "$pid" > /dev/null; then
echo "Program is running with PID $pid"
return 0
else
echo "Stale PID file found: $PID_FILE"
rm "$PID_FILE"
fi
fi
echo "Program is not running"
return 1
}
# 处理命令行参数
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
stop && start
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
;;
esac
exit $? # 设置退出码
JAVA部署脚本
于 2024-06-14 17:48:02 首次发布