为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 ubuntu 中启动、停止和重启 bash 脚本

如何在 ubuntu 中启动、停止和重启 bash 脚本

胡说叔叔 2023-03-31 09:31:45
我有一个在 ubuntu 上运行 java 应用程序的脚本nohup java -Xms512m -Xmx8g -jar /data/software/190716/myapp-0.0.1.jar --server.port=8080 --spring.config.location=/data/software/myapp.properties > ~/running.myapp.log &我可以制作一个.sh脚本来使命令启动、停止和重新启动进程吗?谢谢
查看完整描述

1 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

如评论中所述,更好的方法是遵循running-a-java-process-from-systemd

但是如果你真的对 bash 脚本感兴趣,那么你可以做这样的事情,但请记住,可能有更好的方法。

#!/bin/bash


function start_app() {


    # tested with this , uncomment your command

    nohup node bin/www > logfile.txt  2>&1 & 

    # nohup java -Xms512m -Xmx8g -jar /data/software/190716/myapp-0.0.1.jar --server.port=8080 --spring.config.location=/data/software/myapp.properties

    # write the pid to text to file to use it later

    app_pid=$!

    echo "Process started having PID $app_pid"

    # wait for process to check proper state, you can change this time accordingly 

    sleep 3

    if ps -p $app_pid > /dev/null

    then

        echo "Process successfully running having PID $app_pid"

        # write if success

        echo $app_pid > process_id.txt

    else

        echo "Process stopped before reached to steady state"

    fi

}


function stop_app() {

    # Get the PID from text file

    application_pid=$(cat process_id.txt)

    echo "stopping process, Details:"

    # print details

    ps -p $application_pid

    # check if running

    if ps -p $application_pid > /dev/null

    then

        # if running then kill else print message

        echo "Going to stop process having PId $application_pid"

        kill -9 $application_pid

        if [ $? -eq 0 ]; then

        echo "Process stopped successfully"

        else

        echo "Failed to stop process having PID $application_pid"

        fi

    else

        echo "Failed to stop process, Process is not running"

    fi

}



case "$1" in 

    start_app)   start_app ;;

    stop_app)    stop_app ;;

    restart) stop_app; start_app ;;

    *) echo "usage: $0 start_app|stop_app|restart_app" >&2

       exit 1

       ;;

esac

//img4.sycdn.imooc.com/6426382e0001018d04770360.jpg

查看完整回答
反对 回复 2023-03-31
  • 1 回答
  • 0 关注
  • 276 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信