Common shell scripts for linux service start, stop, status, restart (jenkins as an example)

Time: June 17, 2023 14:59:02

Background : Service start, stop, restart, status management scripts for any non-docker installation on Linux

Applicable to: java

Scenario: Applicable when java starts and stops the service.

What needs to be modified:

1. port:22354, you need to modify it to the port for your own service .

2. The script takes jenkins as an example. In fact, based on this, service management started by any java command can be completed with slight modifications.

3. 256m in JAVA_OPTIONS can be modified to 512m (if resources are sufficient) to avoid subsequent program failure due to insufficient memory.

#!/bin/bash
JAVA_OPTIONS="-server -Xmx256m -Xms256m"
Jenkins=$2
this_dir="$( cd "$( dirname "$0"  )" && pwd )"
log_file="${this_dir}/catalina.out"
jar_file="${this_dir}/${Jenkins}"
 
if [ "$1" = "" ];
then
    echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status} \033[0m"
    exit 1
fi
 
if [ "$Jenkins" = "" ];
then
    echo -e "\033[0;31m 未输入应用名 \033[0m"
    exit 1
fi
 
function start()
{
    count=`ps -ef |grep java|grep $Jenkins|grep -v grep|wc -l`
    if [ $count != 0 ];then
        echo "$Jenkins is running..."
    else
        nohup java $JAVA_OPTIONS -jar  ${jar_file}  --httpPort=22354> "${log_file}" 2>&1 &
        echo -e "Start $Jenkins success...Please see the detail log in /logs/catalina.out"
    fi
}
 
function stop()
{
    echo "Stop $Jenkins"
    boot_id=`ps -ef |grep java|grep $Jenkins|grep -v grep|awk '{print $2}'`
    count=`ps -ef |grep java|grep $Jenkins|grep -v grep|wc -l`
 
    if [ $count != 0 ];then
        kill $boot_id
        count=`ps -ef |grep java|grep $Jenkins|grep -v grep|wc -l`
 
        boot_id=`ps -ef |grep java|grep $Jenkins|grep -v grep|awk '{print $2}'`
        kill -9 $boot_id
    fi
}
 
function restart()
{
    stop
    sleep 2
    start
}
 
function status()
{
    count=`ps -ef |grep java|grep $Jenkins|grep -v grep|wc -l`
    if [ $count != 0 ];then
        echo "$Jenkins is running..."
    else
        echo "$Jenkins is not running..."
    fi
}
 
case $1 in
    start)
    start;;
    stop)
    stop;;
    restart)
    restart;;
    status)
    status;;
    *)
 
    echo -e "\033[0;31m Usage: \033[0m  \033[0;34m sh  $0  {start|stop|restart|status}  {JenkinsJarName} \033[0m
\033[0;31m Example: \033[0m
      \033[0;33m sh  $0  start esmart-test.jar \033[0m"
esac

Guess you like

Origin blog.csdn.net/i_likechard/article/details/131260558