Linux启动jar包 脚本

169 阅读1分钟

使用方式

# 启动jar包
./my.sh demo.jar start
# 重启jar包
./my.sh demo.jar restart
# 停止运行jar包
./my.sh demo.jar stop

启动jar包之后会在jar包所在目录下新建一个 jar包名称.log 的文件夹 里面存放jar包运行的nohub日志.

#!/bin/bash
source /etc/profile
JAR_NAME=$1
PID_FILE="./pid"
JAR_FILE="./${JAR_NAME}"
LOG_DIR="./${JAR_NAME}_log"

function start() {
    if [ -f "$PID_FILE" ] && ps -p $(cat "$PID_FILE") > /dev/null; then
        echo "Process already running with pid: $(cat $PID_FILE)"
    else
        if [ ! -d "$LOG_DIR" ]; then
            mkdir "$LOG_DIR"
        fi
        nohup java -jar "$JAR_FILE" > "$LOG_DIR/$JAR_NAME.log" 2>&1 &
        echo $! > $PID_FILE
        echo "Process started with pid: $(cat $PID_FILE)"
    fi
}

function restart() {
    if [ -f "$PID_FILE" ] && ps -p $(cat "$PID_FILE") > /dev/null; then
        echo "Process is running with pid: $(cat $PID_FILE)"
    else
        echo "Process is not running"
    fi
}

function stop() {
    if [ -f "$PID_FILE" ] && ps -p $(cat "$PID_FILE") > /dev/null; then
        kill $(cat $PID_FILE)
        rm $PID_FILE
        echo "Process stopped"
    else
        echo "Process is not running"
    fi
}

case "$2" in
    start)
        start
        ;;
    restart)
        restart
        ;;
    stop)
        stop
        ;;
    *)
        echo "Usage: $0 {jar-name} {start|status|stop}"
        exit 1
        ;;
esac