This answer applies to Tomcat running as a service on recent versions of Ubuntu. One benefit of a service is that it provides tools for getting clear and unambiguous information on the status of the program.
If Tomcat is running as a systemd
service, which it almost certainly will be if you installed it from the repository on any recent (16.04+) Ubuntu version, you can check if it's running using
systemctl status tomcat9.service
(replacing "9" with whatever version you're using) and visually inspecting the output for the Active:
field, which will be active (running)
if Tomcat is up or inactive (dead)
if Tomcat is down.
This is also easy to script, since the command systemctl status tomcat9.service
does not require sudo
and returns an exit code of 0
if Tomcat is running, or 3
if it is stopped:
# Run the command and suppress the standard output:
systemctl status tomcat9.service > /dev/null 2>&1
# `$?` stores the exit code of the last command,
# which is what we want:
if [ $? -ne 0 ]; then
# Tomcat is down, do whatever.
fi
If you want to restart Tomcat in the event it's down, that's a bit harder to automate, since the command sudo systemctl (start|restart) tomcat9.service
requires sudo
. That's a different question, though.
Prior to systemd
, Tomcat was still installed as a service on Ubuntu as far back as I'm aware. On these systems, the equivalent command is
$ service tomcat9 status
and you can check the exit codes in the same way.