启动、停止、查看某个目录下所有JAR程序脚本

前言

近期工作中有遇到这样一个需求:编写一个脚本用来控制某个目录下所有JAR程序的起停已经查看程序的状态。过程中查阅的大量的资料并实现了功能,借此记录一下。

脚本

1、启动脚本

脚本名称:start.sh

#!/usr/bin/env bash

# 配置文件名称 (该配置文件放置在jar包同级目录下并且必须存在已经配置文件名称具备统一性!!!请根据实际的配置文件名称进行修改)
CONFIG_FILE_NAME="application.yml"

# 启动一个目录下的所有jar包
function read_dir(){
    
    
for file in `ls $1`
do
  #如果当前文件是文件夹则递归处理
  if [ -d $1"/"$file ]
  then
    read_dir $1"/"$file
  else
    # 当前文件不是一个文件夹
    if [[ -f $1"/"$file ]]
    then
        # 如果当前文件是一个.jar结尾的文件则启动它
        if [[ ${file:0-4} == '.jar' ]];
        then
       echo $1/$file 开始启动...
		   nohup java -jar $1"/"$file --spring.config.location=$1"/"$CONFIG_FILE_NAME > /dev/null &
		   echo 启动完成!
        fi
    fi
  fi
done
}
#读取第一个参数
read_dir $1

2、停止脚本

脚本名称:stop.sh

#!/usr/bin/env bash
# 停止一个目录下的所有jar程序
function read_dir(){
    
    
for file in `ls $1`
do
  #如果当前文件是文件夹则递归处理
  if [ -d $1"/"$file ]
  then
    read_dir $1"/"$file
  else
    # 当前文件不是一个文件夹
    if [[ -f $1"/"$file ]]
    then
        if [[ ${file:0-4} == '.jar' ]];
        then
            # 获取pid
	        pid=`ps -ef | grep $1/$file | grep -v grep | awk '{print $2}'`
            # -z 表示如果$pid为空时则输出提示
	        if [ -z $pid ]; then
		        echo ""
                echo "Service $1/$file is not running! It's not necessary to stop it!"
		        echo ""
	        else
	        # 杀死进程
		        kill -9 $pid
		        echo ""
		        echo "Service stop successfully!pid:${pid} which has been killed forcibly!"
		        echo ""
	        fi
        fi
    fi
  fi
done
}
#读取第一个参数
read_dir $1

3、查看状态脚本

脚本名称:status.sh

#!/usr/bin/env bash
# 查看某个目录下所有jar程序的状态
function read_dir(){
    
    
for file in `ls $1`
do
  #如果当前文件是文件夹则递归处理
  if [ -d $1"/"$file ]
  then
    read_dir $1"/"$file
  else
    # 当前文件不是一个文件夹
    if [[ -f $1"/"$file ]]
    then
        if [[ ${file:0-4} == '.jar' ]];
        then
            # 获取pid
	        pid=`ps -ef | grep $1"/"$file | grep -v grep | awk '{print $2}'`
            # -z 表示如果$pid为空时则输出提示
	        if [ -z $pid ];then
		        echo ""
                echo "Service $1"/"$file is not running!"
		        echo ""
	        else
		        echo ""
                echo "Service $1"/"$file is running. It's pids=${pid}"
		        echo ""
	        fi
        fi
    fi
  fi
done
}
#读取第一个参数
read_dir $1

2、使用说明

1、脚本放置的位置

脚本可以放置在任意位置

2、使用方式

2.1、目录结构示例

例如,现在有如下目录结构:

  • Users
    • jiangnan
      • Desktop
        • jarList
          • A
            • test.jar
            • application.yml
          • B
            • test.jar
            • application.yml
          • C
            • test.jar
            • application.yml

2.2、启动/Users/jiangnan/Desktop/jarList/目录下的所有jar程序

sh start.sh /Users/jiangnan/Desktop/jarList/

2.3、停止/Users/jiangnan/Desktop/jarList/目录下的所有jar程序

sh stop.sh /Users/jiangnan/Desktop/jarList/

2.4、查看/Users/jiangnan/Desktop/jarList/目录下的所有jar程序的运行状态

sh status.sh /Users/jiangnan/Desktop/jarList/

猜你喜欢

转载自blog.csdn.net/ScholarTang/article/details/112528573
今日推荐