Java服务启动、重启、停止shell脚本模板
需求来源脚本编写样板需求来源
日常开发部署时,往往需要对打包的程序进行启动、重启、停止等工作重复操作,因此针对简化使用需要设置shell脚本。
脚本编写样板
在服务目录中,vim server.sh
新建shell文件。
然后编写如下内容:
#!/bin/bashapp='java-crawler-recruit-1.0.0.jar'args='-Xms512m -Xmx512m'cmd=$1pid=`ps -ef |grep $app | grep -v 'grep'| awk '{print $2}'`startup(){nohup java -jar $args $app > logs/server.log &}if [ ! $cmd ]; thenecho "Please specify args 'start|restart|stop'"exitfiif [ $cmd == 'start' ]; thenif [ ! $pid ]; thenstartupelseecho "$app is running! pid=$pid"fifiif [ $cmd == 'restart' ]; thenif [ $pid ]thenecho "$pid will be killed after 2 seconds!"sleep 2kill -9 $pidfistartupfiif [ $cmd == 'stop' ]; thenif [ $pid ]; thenecho "$pid will be killed after 2 seconds!"sleep 2kill -9 $pidfiecho "$app is stopped"fi
使用说明:
需要将 app 和 args 改成对应项目的配置,app为jar包名,args为jvm启动参数设置执行chmod +x server.sh
添加运行权限执行./server.sh start
或者./server.sh restart
即可启动项目执行./server.sh stop
停止项目运行
启动报错问题解决:
错误为:/bin/bash^M: 坏的解释器: 没有那个文件或目录
。
出现原因:Windows 下编写的 shell 脚本,里面的换行符,在 Linux 下表达的含义不一致,多了些 Linux 无法解析的字符。
如何查看:
cat -A 文件名
,例如:cat -A server.sh
。
如何解决多余的字符:
sed -i 's/\r$//' 文件名
,例如:sed -i 's/\r$//' server.sh
此时使用时就恢复正常了。