一、背景
有时一些临时测试的程序,如果每次都手动java -jar太麻烦了,而且不便于管理状态。
因此做一个完整的 Bash 脚本,可以用来管理你的xxxx.jar 应用程序。这个脚本提供了启动、停止、重启和查看状态的功能,各位把脚本中的jar名和路径换成自己的就可以直接使用。
二、操作步骤
1、vi 一个脚本
vi /root/cgh/cgh-tools/cgh-tools.sh
2、给脚本添加可执行权限
chmod +x /root/cgh/cgh-tools/cgh-tools.sh
3、创建符号链接到 /usr/local/bin 以便全局使用
ln -s /root/cgh/cgh-tools/cgh-tools.sh /usr/local/bin/cgh-tools
4、具体脚本内容
#!/bin/bash
# 定义变量
JAR_NAME="cgh-tools-1.0.0.jar"
JAR_PATH="/root/cgh/cgh-tools/$JAR_NAME"
LOG_FILE="/root/cgh/cgh-tools/cgh-tools.log"
PID_FILE="/root/cgh/cgh-tools/cgh-tools.pid"
JAVA_OPTS="-Xms256m -Xmx512m" # 可根据需要调整JVM参数
# 检查Java是否安装
check_java() {
if ! command -v java &> /dev/null; then
echo "Java is not installed. Please install Java first."
exit 1
fi
}
# 启动服务
start() {
check_java
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if ps -p $PID > /dev/null; then
echo "Service is already running (PID: $PID)"
return
fi
fi
echo "Starting $JAR_NAME..."
nohup java $JAVA_OPTS -jar "$JAR_PATH" >> "$LOG_FILE" 2>&1 &
echo $! > "$PID_FILE"
echo "Service started (PID: $!)"
}
# 停止服务
stop() {
if [ ! -f "$PID_FILE" ]; then
echo "Service is not running (PID file not found)"
return
fi
PID=$(cat "$PID_FILE")
if ps -p $PID > /dev/null; then
echo "Stopping service (PID: $PID)..."
kill $PID
rm -f "$PID_FILE"
echo "Service stopped"
else
echo "Service is not running (process not found)"
rm -f "$PID_FILE"
fi
}
# 重启服务
restart() {
stop
sleep 2
start
}
# 查看服务状态
status() {
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if ps -p $PID > /dev/null; then
echo "Service is running (PID: $PID)"
return
else
echo "Service is not running (stale PID file)"
return
fi
fi
echo "Service is not running"
}
# 查看日志
log() {
tail -f "$LOG_FILE"
}
# 帮助信息
usage() {
echo "Usage: $0 {start|stop|restart|status|log}"
exit 1
}
# 主逻辑
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status
;;
log)
log
;;
*)
usage
;;
esac
exit 0
三、使用方法
启动服务:
cgh-tools start
停止服务:
cgh-tools stop
重启服务:
cgh-tools restart
查看状态:
cgh-tools status
查看实时日志:
cgh-tools log