Shell

shell

  • 创建文件
touch app.sh
  • 编写脚本
#!/bin/bash

#启动脚本

#应用名称
APP_NAME=$1

#使用说明,提示用户输入参数
usage() {
   echo "Usage: sh app [APP_NAME] [start|stop|restart|status]"
# 1 表示非正常运行结束退出
   exit 1
}

#校验函数(是否运行)
# $0 表示当前脚本名称
is_exist(){
	#获取PID
	PID=$(ps -ef |grep ${APP_NAME} |grep -v $0 |grep -v grep |awk '{print $2}')
	if [ -z "${PID}" ]; then
		return 1
	else
		return 0
	fi 
}

#启动函数
start(){
	is_exist
	if [ $? -eq "0" ]; then
		echo "${APP_NAME} is already running, pid=${PID}"
	else
		nohup java -jar ${APP_NAME}>/log/${APP_NAME}.log &
		PID=$(echo $!)
		echo "${APP_NAME} start success, PID=$!"
	fi
}

#停止函数
stop(){
	is_exist
	if [ $? -eq "0" ]; then
		kill -9 ${PID}
		echo "${APP_NAME} process stop, PID=${PID}"
	else
		echo "There is not the process of ${APP_NAME}"
	fi
}

#重启函数
restart(){
	stop
	start
}

#查看状态函数
status(){
	is_exist
	if [ $? -eq ""0 ]; then
		echo "${APP_NAME} is running, PID=${PID}"
	else
		echo "There is not the process of ${APP_NAME}"
	fi
}

#根据第二个参数决定启用的脚本
case $2 in
"start")
	start
	;;
"stop")
	stop
	;;
"restart")
	restart
	;;
"status")
	status
	;;
   *)
   usage
   ;;
esac
# 0 为正常运行结束退出
exit 0 
  • 赋予脚本权限
#绿色文件表示可执行
chmod +x app.sh
  • 使用脚本
#开启
./app.sh xxx.jar start

#关闭
./app.sh xxx.jar stop
原文地址:https://www.cnblogs.com/qifengle1412/p/13026292.html