Bash scripts to start and stop Apache Tomcat

Introduction

In attempting to convert my Java knowledge into a web technology, i.e. learning Java web applications I have found that starting and stopping Apache Tomcat with the commands “/Library/Tomcat/bin/startup.sh” and “/Library/Tomcat/bin/shutdown.sh” (on MacOS) a little long winded for my memory.

Solution

By creating two simple bash scripts I can now start and stop Apache Tomcat using the commands “tomcat_start” and “tomcat_stop” respectively.

First of all the necessary command to start the Tomcat service (assuming the Tomcat scritps are stored in /Library/Tomcat/bin/)

/Library/Tomcat/bin/startup.sh &>/dev/null &disown

Straight after starting the service, a message can be printed

printf "\n\nStarting apache tomcat\n"

Then to allow the Tomcat service time to startup, the bash script can be put to sleep for 5 seconds (5 seconds is probably a little overkill as Tomcat starts pretty quickly)

sleep 5

Finally, an interesting section of code to check if the Tomcat service has been started. This simply checks the response of localhost port 8080 (the port used by Tomcat) and responds with a message depending on the result.

if curl --output /dev/null --silent --head --fail http://localhost:8080/
  then
    echo "Tomcat is now running"
  else
    echo "Tomcat could not be started"
fi

Completed files

Gist created by: f13dev
Created at: 18 September 2016 | Last edited: 18 September 2016 | View on GitHub
Description: Bash script to start and/or stop Apache Tomcat on MacOS. Place these files in "/usr/local/bin" and mark each executable using "chmod +x filename".

Files (2)
tomcat_start (0.44kb) Download file
#Start tomcat
/Library/Tomcat/bin/startup.sh &>/dev/null &disown

#print message
printf "\n\nStarting apache tomcat\n"

#sleep for 5 seconds
sleep 5

#Check if tomcat has started (localhost:8080 should succeed)
if curl --output /dev/null --silent --head --fail http://localhost:8080/
then
echo "Tomcat is now running"
else
echo "Tomcat could not be started"
fi

#Add a couple of new lines to neaten up the appearance
printf "\n\n"
tomcat_stop (0.45kb) Download file
#Stop tomcat
/Library/Tomcat/bin/shutdown.sh &>/dev/null &disown

#print message
printf "\n\nStopping apache tomcat\n"

#sleep for 5 seconds
sleep 5

#Check if tomcat has stopped (localhost:8080 should return an error)
if curl --output /dev/null --silent --head --fail http://localhost:8080/
then
echo "Tomcat could not be stopped"
else
echo "Tomcat is no longer running"
fi

#Add a couple of new lines to neaten up the appearance
printf "\n\n"

Comments: 0

Leave a Reply