Scenes
When you want to run a Jar program you wrote on a server (Linux), the usual approach is
java -jar config.jar
#或者让其后台启动
nohup java -jar config.jar &
This will allow the program to start. However, this is not user-friendly or elegant enough. A better way would be to first determine config.jar
whether it is already running, and only execute startup if it is not running.
plan
#!/bin/sh
#NAME变量填写jar包的名字,尽可能唯一
NAME="config.jar"
RUN=0
#循环,为了让脚本一直运行监控
while [ $RUN -eq 0 ]
do
DTTERM=`jps | grep $NAME` #匹配程序
if [ -n "$DTTERM" ]
then
echo "PID=$( jps | grep "$NAME") is running..."
RUN=$(( $RUN + 1 ))
#正确输入信息到日志文件
else
filepath=$(cd "$(dirname "$0")"; pwd)
echo "$NAME is not start! Going to start(dir=$filepath)..."
echo > $filepath/log.out && nohup java -jar $filepath/$NAME > $filepath/log.out &
fi
sleep 2 # 每次监测时间60秒
done
exit 0
Save the above code as start.sh
, in config.jar
the same directory, with the following structure
and grant permission
chmod +x start.sh
Then execute
root@xxxxxx# sh start.sh
PID=4232 config.jar is running...