Write a Shell script to monitor the running status of the jar

1. Create a shell file and edit the content as follows

#!/bin/bash
port=10009 
jar_name=/home/data/myqxin/hpmis-0.0.1-SNAPSHOT.jar

#运行脚本提示信息
tips(){
    
    
 echo "------------------"
 echo ""
 echo "服务器端口:${port}"
 echo "jar包路径:${jar_name}"
 echo ""
 echo "可执行命令参数"
 echo "-status -查看当前服务运行状态"
 echo "-start -启动服务"
 echo "-stop -停止服务"
 echo "-restart -重启服务"
 echo ""
 echo "------------------"
}

#查询状态
status(){
    
    
  #查询端口的PID {print $7{取出打印的第7个值
  pid=$(netstat -nlp |grep :$port | awk '{print $7}' | awk -F"/" '{ print $1 }')
  #判断端口是否被占用
  if [ -z "${pid}" ];then
	echo "没有项目在运行"
  else
  	echo "项目正在运行"	  
  fi
}

#启动服务
start(){
    
    
  pid=$(netstat -nlp |grep :$port | awk '{print $7}' | awk -F"/" '{ print $1 }')
  if [ -z "${pid}" ];then
	echo "正在启动......"
	/home/data/jdk/bin/java -jar $jar_name --spring.profiles.active=test > log.log &
  else
	echo "项目运行中或端口已被占用"
  fi
}

#停止服务
stop(){
    
    
  pid=$(netstat -nlp |grep :$port | awk '{print $7}' | awk -F"/" '{ print $1 }')
  if [ -z "${pid}" ];then
	echo "没有项目正在运行,请先启动"
  else
	kill -9 $pid
	echo "已杀死端口为${port} 的应用"
  fi
}

#重启服务
restart(){
    
    
  pid=$(netstat -nlp |grep :$port | awk '{print &7}' | awk -F"/" '{ print $1 }')
  echo "正在杀死端口 ${port} 的pid ${pid} 中..."
  if [ -z "${pid}" ];then
	echo "服务未启动"
  else
 	kill -9 $pid
  fi
  sleep 5
  start
  echo "服务重启成功"
}

# 参数选项
case "$1" in
 "-status")
  status
  ;;
 "-start")
  start
  ;;
 "-stop")
  stop
  ;;
 "-restart")
  restart
  ;;
 *)
  tips
  ;;
esac

2. Give the script permission

chmod 777 xxx.sh

3. Execute the demo

insert image description here
insert image description here
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/qq_45752401/article/details/127786241