Shell编程
自动化部署脚本
#!/bin/bash
APP_LOCATION="./appTest.jar"
APP_NAME="appTest"
PID_CMD="ps -ef |grep $APP_NAME |grep -v grep |awk '{print \$2}'"
start() {
echo "----------------------------------start----------------------------------"
PID=$(eval $PID_CMD)
if [[ -n $PID ]]; then
echo "$APP_NAME is already running,PID is $PID"
else
nohup java -jar $APP_LOCATION > ./log.txt 2>&1 &
sleep 2
PID=$(eval $PID_CMD)
if [[ -n $PID ]]; then
echo "Start $APP_NAME successfully,PID is $PID"
else
echo "Failed to start $APP_NAME !!!"
fi
fi
echo "----------------------------------start----------------------------------"
}
stop() {
echo "----------------------------------stop------------------------------------"
PID=$(eval $PID_CMD)
if [[ -n $PID ]]; then
kill -15 $PID
sleep 5
PID=$(eval $PID_CMD)
if [[ -n $PID ]]; then
kill -9 $PID
sleep 2
echo "Stop $APP_NAME successfully by kill -9 $PID"
else
echo "Stop $APP_NAME successfully by kill -15 $PID"
fi
else
echo "$APP_NAME is not running!!!"
fi
echo "----------------------------------stop------------------------------------"
}
restart() {
echo "----------------------------------restart------------------------------------"
stop
start
echo "----------------------------------restart------------------------------------"
}
status() {
echo "----------------------------------status------------------------------------"
PID=$(eval $PID_CMD)
if [[ -n $PID ]]; then
echo "$APP_NAME is running,PID is $PID"
else
echo "$APP_NAME is not running!!!"
fi
echo "----------------------------------status------------------------------------"
}
info() {
echo "----------------------------------info------------------------------------"
echo "APP_LOCATION: $APP_LOCATION"
echo "APP_NAME: $APP_NAME"
#echo "JDK_HOME: $JDK_HOME"
#echo "VM_OPTS: $VM_OPTS"
#echo "SPB_OPTS: $SPB_OPTS"
echo "----------------------------------info------------------------------------"
}
help() {
echo "----------------------------------help------------------------------------"
echo "start: start server"
echo "stop: shutdown server"
echo "restart: restart server"
echo "status: display status of server"
echo "info: display info of server"
echo "help: help info"
echo "----------------------------------help------------------------------------"
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status
;;
info)
info
;;
help)
help
;;
*)
help
;;
esac
exit $?
踩坑
// 注意[[]]内的空格
if [[ -n $PID ]]; then
// 注意{print \$2}转义字符
PID_CMD="ps -ef |grep $APP_NAME |grep -v grep |awk '{print \$2}'"
PID=$(eval $PID_CMD)
参考文章
【1】shell 语法
【2】shell脚本部署实战