shell脚本
#!/bin/sh
APP_NAME=my-app.jar
CONFIG_LOCATION=/webapp/my_app/application.yml
usage(){
echo "Usage: sh my-app.sh [start|stop|restart|status]"
exit 1
}
is_exist(){
pid=`ps -ef | grep $APP_NAME | grep -v grep | awk '{print $2}'`
if [ -z "${pid}" ]; then
return 0
else
return 1
fi
}
start(){
is_exist
if [ $? -eq "1" ]; then
echo "${APP_NAME} is running now, can not start again."
else
echo "Start Process"
nohup java -jar $APP_NAME --spring.config.location=$CONFIG_LOCATION >/dev/null 2>&1 &
is_exist
if [ $? -eq "1" ]; then
echo "Start Success!"
else
echo "Start Fail!"
fi
fi
}
stop() {
is_exist
if [ $? -eq "1" ]; then
kill -15 $pid
sleep 5
is_exist
if [ $? -eq "1" ]; then
echo "Kill Process!"
kill -9 $pid
else
echo "Stop Success!"
fi
else
echo "${APP_NAME} is not running"
fi
}
status() {
is_exist
if [ $? -eq "1" ]; 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
运行脚本
sh my-app.sh status
sh my-app.sh start
sh my-app.sh restart
sh my-app.sh stop
关于 nohup 命令
nohup 是 no hang up 的缩写,就是不挂断的意思。
该命令可以在你退出帐户/关闭终端之后继续运行相应的进程,在缺省情况下该作业的所有输出都被重定向到一个名为nohup.out的文件中。
案例
nohup command > myout.file 2>&1 &
在上面的例子中
- 0 – stdin (standard input)
- 1 – stdout (standard output)
- 2 – stderr (standard error)
2>&1是将标准错误(2)重定向到标准输出(&1),标准输出(&1)再被重定向输入到myout.file文件中。
关于/dev/null
这是一个无底洞,任何东西都可以定向到这里,但是却无法打开。 所以当你不关心日志输出的时候可以利用stdout和stderr定向到这里>./command.sh >/dev/null 2>&1 。
nohup和&的区别
- & : 指在后台运行
- nohup : 不挂断的运行,注意并没有后台运行的功能。就是指,用nohup运行命令可以使命令永久的执行下去,和用户终端没有关系,例如我们断开SSH连接都不会影响他的运行,注意了nohup没有后台运行的意思;&才是后台运行
参考资料
https://blog.csdn.net/weixin_40991408/article/details/88997180
https://blog.csdn.net/whh18254122507/article/details/78011713
https://www.cnblogs.com/jinxiao-pu/p/9131057.html
https://www.cnblogs.com/keystone/p/11159665.html