最近部署项目写了一个shell脚本用于文件夹内jar文件的一键启动和停止,包括状态查询等;和大家共享一下!
贴上代码:
#!/bin/bash
version="1.0.1";
JAVA=java
JAVA_HOME=/opt/jdk1.8
JAVA=$JAVA_HOME/bin/java
appName=$2
if [ -z $appName ];then
appName=`ls -t |grep .jar$ |head -n1`
fi
#一键启动
function start()
{
count=`ps -ef |grep java|grep $appName|wc -l`
if [ $count != 0 ];then
echo "Maybe $appName is running, please check it..."
else
echo "The $appName is starting..."
nohup $JAVA -Xmx2048m -Xms1024m -XX:PermSize=512M -XX:MaxNewSize=512M -XX:MaxPermSize=1024M -jar ./$appName > ./console.out 2>&1 &
fi
}
#一键结束
function stop()
{
appId=`ps -ef |grep java|grep $appName|awk '{print $2}'`
if [ -z $appId ];then
echo "Maybe $appName not running, please check it..."
else
echo "The $appName is stopping..."
kill $appId
fi
}
#一键重启
function restart()
{
# get release version
releaseApp=`ls -t |grep .jar$ |head -n1`
# get last version
lastVersionApp=`ls -t |grep .jar$ |head -n2 |tail -n1`
appName=$lastVersionApp
stop
for i in {5..1}
do
echo -n "$i "
sleep 1
done
echo 0
backup
appName=$releaseApp
start
}
#一键备份
function backup()
{
# get backup version
backupApp=`ls |grep -wv $releaseApp$ |grep .jar$`
# create backup dir
if [ ! -d "backup" ];then
mkdir backup
fi
# backup
for i in ${backupApp[@]}
do
echo "backup" $i
mv $i backup
done
}
#状态查询
function status()
{
appId=`ps -ef |grep java|grep $appName|awk '{print $2}'`
if [ -z $appId ]
then
echo -e "\033[31m Not running \033[0m"
else
echo -e "\033[32m Running [$appId] \033[0m"
fi
}
#菜单
function usage()
{
echo "Usage: $0 {start|stop|restart|status|stop -f}"
echo "Example: $0 start"
exit 1
}
case $1 in
start)
start;;
stop)
stop;;
restart)
restart;;
status)
status;;
*)
usage;;
esac