需要配置端口号和jar包名称,如下为8080和web.jar
自动获取当前路径,jar包放在同脚本目录下的版本目录(eg:1.0.0)中,
自动使用kill-15自动杀死对应端口的进程,5秒后未杀死可以使用kill-9强制杀死进程,
最后选择性输出启动日志。
脚本如下:
#!/bin/bash
# 读取端口号
port=8080
baseDir=$(pwd)
dir=$1
project="web.jar"
# 确认端口号
echo "[ warn] Is the port($port) right? [Y/N]"
read isPortOk
if [ "$isPortOk" != "Y" ]; then
echo '[ info] exit.'
exit 0;
fi
echo '[ info] port is '$port
# 输入 jar 所在文件夹名称
if [ "$dir" == "" ]; then
echo "[ warn] input dir name. eg: 1.0.1"
read dir
if [ "$dir" == "" ]; then
echo '[ error] exit.'
exit 0;
fi
fi
# 绝对路径
fullFilePath=$baseDir/$dir/$project
logFilePath="$baseDir/$dir/log.out"
# 确认 jar包位置
echo "[ warn] Is project right, path is $fullFilePath? [Y/N]"
read isProjectPathOk
if [ "$isProjectPathOk" != "Y" ]; then
echo '[ info] exit.'
exit 0;
fi
# 校验文件是否存在
if [ ! -f "$fullFilePath" ];then
echo "[ error] project file not exist.";
echo '[ info] exit.'
exit 0;
fi
getPID() {
curPid=$(netstat -nlp|grep $1 | awk '{print $7}' | awk -F"/" '{print $1}');
echo $curPid
}
startProject() {
echo "[ warn] Is start project? [Y/N]"
read isStart
if [ "$isStart" != "Y" ]; then
echo '[ info] exit.'
exit 0;
fi
echo '[ info] start project, waiting....'
#nohup java -jar $fullFilePath > $logFilePath 2>&1 &
nohup java -jar -server -Xms512m -Xmx512m -XX:CompressedClassSpaceSize=128m -XX:MetaspaceSize=200m -XX:MaxMetaspaceSize=200m $fullFilePath > $logFilePath 2>&1 &
echo "[ info] logger path is $logFilePath"
echo "[ info] Is show logger? [Y/N]"
read isShowLogger
if [ "$isShowLogger" != "Y" ]; then
echo '[ info] exit.'
exit 0;
fi
tail -f $logFilePath
echo '[ info] start success.'
}
echo '[ info] '$(netstat -nlp|grep :$port)
# 第一次 kill -15
pid=$(getPID $port);
if [ $pid ]; then
echo "[ info] pid is $pid"
echo "[ warn] run kill -15 $pid? [Y/N]"
read isKillPid
if [ "$isKillPid" != "Y" ]; then
echo '[ info] exit.'
exit 0;
fi
echo '[ info] killing, waiting....'
kill -15 $pid
else
echo '[ info] first: no pid, will start.'
# 调用启动方法
startProject
# 启动后退出
exit 0
fi
sleep 5
# 第二次 kill -9, 第一次 没杀掉
pid=$(getPID $port);
if [ $pid ]; then
echo "[ info] pid is $pid"
echo "[ warn] run kill -9 $pid? [Y/N]"
read isKill
if [ "$isKill" != "Y" ]; then
echo '[ info] exit.'
exit 0;
fi
echo '[ info] killing, waiting....'
kill -9 $pid
else
echo '[ info] second: no pid, will start.'
# 调用启动方法
startProject
# 启动后退出
exit 0
fi
sleep 5
# 第三次获取 pid 判断是否kill掉进程
pid=$(getPID $port);
if [ $pid ]; then
echo '[ warn] last: PID is '$pid
echo '[ error] last: This process cannot be killed. pid is' $pid
else
echo '[ info] last: no pid, will start.'
# 调用启动方法
startProject
# 启动后退出
exit 0
fi