linux jar包自动部署脚本


环境中需要有git、maven、java,并且git能连接到仓库

创建两个文件

vim jar.sh

将下面的内容复制粘贴

ESC

Shift+:

wq

回车保存

#!/bin/bash
#######################
#脚本使用方法:
#本脚本和jar包在同一目录下,保证当前目录有且只有一个jar包即可。无需修改任何东西。
# Usage: $0 {start|stop|status|restart|log}
#######################
#可在此处添加需要加载的环境变量
#######################

if ls *.jar &>/dev/null; then
  if [ $(ls *.jar | wc -l) -eq 1 ]; then
    APP_NAME=$(find -maxdepth 1 -name "*.jar")
  else
    echo -e "\033[31m------   Error! Too Much JAR Packages In This Directory !\033[0"
    exit 2
  fi
else
  echo -e "\033[31m------   Error! No JAR Package In Current Directory !\033[0"
  exit 1
fi

exist() {
  pid=$(ps aux | grep "$APP_NAME" | grep -v grep | grep "jar$" | awk '{print $2}')
  if [ -z "$pid" ]; then
    return 1
  else
    return 0
  fi
}
start() {
  exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} is already running. pid is ${pid}."
  else
    nohup java -jar "$APP_NAME" &>nohup.out &
  fi
}
stop() {
  exist
  if [ $? -eq 0 ]; then
    kill -9 "$pid"
  else
    echo "${APP_NAME} is not running"
  fi
}
status() {
  exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} is running. pid is ${pid}."
  else
    echo "${APP_NAME} is not running"
  fi
}
log() {
  tail -9999f nohup.out
}

case $1 in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  stop
  start
  ;;
status)
  status
  ;;
log)
  log
  ;;
*)
  echo "Usage: $0 {start|stop|status|restart|log}"
  ;;
esac

vim redeploy.sh

将下面的内容复制粘贴保存

#!/bin/bash
#仓库路径
repository_dir='/project/matelinepickservice'
#项目部署路径
project_dir=$(pwd)
#需要复制过去的文件列表
copy_file_list=('auto-pick-service.jar' 'app-release.apk' 'application.yaml')
#拉取项目
git --git-dir="${repository_dir}/.git" --work-tree="${repository_dir}/" pull
#maven打包
mvn -f "${repository_dir}/pom.xml" -DskipTests=true clean package
#复制文件到项目部署路径
for file in ${copy_file_list[*]}; do
  \cp -rf "${repository_dir}/target/${file}" "${project_dir}/${file}"
  chmod -R 755 "${project_dir}/${file}"
done
source "${project_dir}/jar.sh" restart

然后将两个文件放在需要部署的目录下,redeploy.sh脚本中的仓库路径需要自己配置,git仓库需要设置记住密码,配置完成之后执行 sh redeploy.sh就可以自动拉取项目并自动部署运行

jar.sh还有别的一些功能,方便调试