January 19, 2017

Restart, Start and Stop Tomcat using Bash

$CATALINA_PID is the Environment Variable that has path of the file which should contains the pid of the catalina/tomcat startup java process.

Typically, this will be under /bin folder in your Tomcat installation.

For example, you could have this in your ~/.bashrc
CATALINA_BASE="/opt/tomcat8"
export CATALINA_BASE
CATALINA_PID="$CATALINA_BASE/bin/catalina.pid"
export CATALINA_PID

By having this $CATALINA_PID environment variable set up, we can easily get the pid of the Tomcat process and control it as we want.

I created two scripts
(1) check-tomcat : To check if Tomcat is running, by reading the Tomcat PID file
(2) restart-tomcat : To kill the tomcat, clear the Tomcat's work folder and restart Tomcat


check-tomcat
============
#!/bin/bash
#title           : check-tomcat
#description     : This script will check if Tomcat is running and return the pid
#author : Raf
#note : Requires $CATALINA_BASE/bin/catalina.pid to be created and $CATALINA_PID to be set.

clear 

if [ -f "$CATALINA_PID" ]; then
read kpid < "$CATALINA_PID"
    
    if ps --pid $kpid 2>&1 1>/dev/null; then
        echo "Tomcat is already running at ${kpid}"
    else
        echo "$CATALINA_PID found, but Tomcat is not running"
    fi
fi


restart-tomcat
==============
#!/bin/bash
#title           : restart-tomcat
#description     : This script will first clear the work folder and then check if Tomcat is running, kill it, and restart the tomcat again
#author : Raf
#note : Requires $CATALINA_BASE/bin/catalina.pid to be created and $CATALINA_PID to be set.


echo "Clear Tomcat log...."
rm -fv /opt/apache-tomcat-8.0.39/logs/catalina.out 
touch /opt/apache-tomcat-8.0.39/logs/catalina.out

echo "Clear Tomcat work folder...."
rm -rfv /opt/apache-tomcat-8.0.39/work/Catalina/

if [ -f "$CATALINA_PID" ]; then
read kpid < "$CATALINA_PID"
    
if ps --pid $kpid 2>&1 1
/opt/apache-tomcat-8.0.39/bin/catalina.sh start;

read kpid < "$CATALINA_PID"
echo "Tomcat is started at ${kpid}"
else
    echo "Killing Tomcat...."
kill -kill $kpid

/opt/apache-tomcat-8.0.39/bin/catalina.sh start;

read kpid < "$CATALINA_PID"
echo "Tomcat is started at ${kpid}"
fi
fi