Please wait...

小波Note

四川 · 成都市多云14 ℃
English

Java Jar package run script

成都Wed, July 10, 2024 at 2 PM1.90k110Estimated reading time 3 min
QR code
FavoriteCtrl + D

Content description prompt

The first line needs to write the name of your own jar package, or you can change it to read the sh file name, which is also possible

Line 29 can add your own jvm related parameters

operation:sh it-fb.sh start|stop|restart|status

it-fb.sh
        API_NAME=it-fb-1.0.0.jar
JAR_NAME=./$API_NAME
#PID represents the PID file
PID=$API_NAME\.pid
 
#Instructions for use, used to prompt input parameters
usage() {
    echo "Usage: sh 执行脚本.sh [start|stop|restart|status]"
    exit 1
}
 
#Check if the program is running
is_exist(){
  pid=`ps -ef|grep $JAR_NAME|grep -v grep|awk '{print $2}' `
  #Return 1 if it does not exist, return 0 if it exists    
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}
 
#启动方法
start(){
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> ${JAR_NAME} is already running PID=${pid} <<<"
  else
    nohup java -Xms256m -Xmx512m -jar $JAR_NAME >> ./$API_NAME\.log 2>&1 &
    echo $! > $PID
    echo ">>> start $JAR_NAME successed PID=$! <<<"
   fi
  }
 
#停止方法
stop(){
  #is_exist
  pidf=$(cat $PID)
  #echo "$pidf" 
  echo ">>> api PID = $pidf begin kill $pidf <<<"
  kill $pidf
  rm -rf $PID
  sleep 2
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> api 2 PID = $pid begin kill -9 $pid  <<<"
    kill -9  $pid
    sleep 2
    echo ">>> $JAR_NAME process stopped <<<" 
  else
    echo ">>> ${JAR_NAME} is not running <<<"
  fi 
}
 
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> ${JAR_NAME} is running PID is ${pid} <<<"
  else
    echo ">>> ${JAR_NAME} is not running <<<"
  fi
}
 
restart(){
  stop
  start
}
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac
exit 0

    
Collapse
Astral