linux服务start、stop、status、restart的通用shell脚本(jenkins为例)

时间:2023年6月17日14:59:02

背景:linux上的任意非docker式安装时的服务start、stop、restart、status管理脚本

适用:java

场景:java启动停止服务时适用。

需要修改内容:

1、port:22354,需要修改为你自己服务的端口

2、脚本是以jenkins为例。实际可以基于此,稍微修改即可完成 任意java 命令启动的服务管理。

3、JAVA_OPTIONS中的256m可以修改为512m(如果资源够用) ,以免后续程序因为内存不足导致任务失败

#!/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

你可能感兴趣的:(jenkins,linux,运维)