Skip to content

Instantly share code, notes, and snippets.

@orvyl
Created January 27, 2018 15:06
Show Gist options
  • Save orvyl/b408ec6b6c8a038517395958914a72ac to your computer and use it in GitHub Desktop.
Save orvyl/b408ec6b6c8a038517395958914a72ac to your computer and use it in GitHub Desktop.
Java Application bash script for start/stop/restart
#! /bin/sh
# Logging
LOG_PATH=logs
LOG_FILE=application.log
mkdir -p $LOG_PATH
# Location of the pid file.
PIDDIR="."
PIDFILE="$PIDDIR/app.pid"
pid=""
getpid() {
if [ -f "$PIDFILE" ]
then
if [ -r "$PIDFILE" ]
then
pid=`cat "$PIDFILE"`
if [ "X$pid" != "X" ]
then
pidtest=`ps -p $pid -o args | grep java | tail -1`
if [ "X$pidtest" = "X" ]
then
rm -f "$PIDFILE"
echo "Delete stale pid file"
pid=""
fi
fi
fi
fi
}
testpid() {
pid=`ps -p $pid | grep $pid | grep -v grep | awk '{print $1}' | tail -1`
if [ "X$pid" = "X" ]
then
# Process is gone so remove the pid file.
rm -f "$PIDFILE"
pid=""
fi
}
start() {
echo "Starting application..."
getpid
if [ "X$pid" = "X" ]
then
CMD="nohup java -jar *.jar >> $LOG_PATH/$LOG_FILE 2>&1 &"
eval $CMD
else
echo "Application already running."
exit 1
fi
sleep 10
getpid
if [ "X$pid" != "X" ]
then
echo "Application started!"
else
echo "Application did not start after 10 seconds. Check $LOG_PATH/$LOG_FILE"
fi
}
stopit() {
echo "Stopping application..."
getpid
if [ "X$pid" = "X" ]
then
echo "Application not running."
else
kill $pid
if [ $? -ne 0 ]
then
echo "Unable to stop application."
exit 1
fi
savepid=$pid
CNT=0
TOTCNT=0
while [ "X$pid" != "X" ]
do
# Show a waiting message every 5 seconds.
if [ "$CNT" -lt "5" ]
then
CNT=`expr $CNT + 1`
else
echo "Waiting for application to exit..."
CNT=0
fi
TOTCNT=`expr $TOTCNT + 1`
sleep 1
testpid
done
pid=$savepid
testpid
if [ "X$pid" != "X" ]
then
echo "Failed to stop application."
exit 1
else
echo "Stopped application."
fi
fi
}
status() {
getpid
if [ "X$pid" = "X" ]
then
echo "Application is not running."
exit 1
else
echo "Application is running ($pid)."
exit 0
fi
}
case "$1" in
'start')
start
;;
'stop')
stopit
;;
'restart')
stopit
start
;;
'status')
status
;;
*)
echo "Usage: $0 { start | stop | restart | status }"
exit 1
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment