#!/bin/bash
#这里可替换为你自己的执行程序,其他代码无需更改
APP_NAME=common.jar
#使用说明,用来提示输入参数
usage() {
echo "Usage: sh 脚本名.sh [start|stop|restart|status]"
exit 1
}
#检查程序是否在运行
is_exist(){
pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' `
#如果不存在返回1,存在返回0
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 > /dev/null 2>&1 &
fi
}
#停止方法
stop(){
is_exist
if [ $? -eq "0" ]; then
kill -9 $pid
else
echo "${APP_NAME} is not running"
fi
}
#输出运行状态
status(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is running. Pid is ${pid}"
else
echo "${APP_NAME} is NOT running."
fi
}
#重启
restart(){
stop
start
}
#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
usage
;;
esac
注释:
一、用途:nohup表示永久运行。&表示后台运行
在应用Unix/Linux时,我们一般想让某个程序在后台运行,nohup ./start-mysql.sh &
该命令的一般形式为:nohup command &
在缺省情况下该作业的所有输出都被重定向到一个名为nohup.out的文件中,除非另外指定了输出文件:
nohup command > myout.file 2>&1 &
在上面的例子中,输出被重定向到myout.file文件中。
二、>/dev/null 2>&1
/dev/null 代表空设备文件,也就是不输出任何信息到终端,说白了就是不显示任何信息。
> 代表重定向到哪里
1 表示stdout标准输出,系统默认值是1,所以">/dev/null"等同于"1>/dev/null"
2 表示stderr标准错误
& 表示等同于的意思,2>&1,表示2的输出重定向等同于1
nohup ./mqnamesrv >/home/cxb/mqnamesrv.out 2>&1 &
即标准输出到mqnamesrv.out中,接着,标准错误输出重定向等同于标准输出,输出到同一文件中。
三、使用 jobs 查看任务。
使用 fg %n 关闭。
四、sh xxx.sh与./xxx.sh区别
sh xxx.sh是用sh 执行start.sh,start.sh可以没有执行标志,可以不用加./,可以不用在脚本第一行写上#!/bin/sh
./start.sh是调用脚本第一行制定的shell去解释执行,缺省为sh,就是bash