Gopinagh.R Gopinagh.R - 8 months ago 116
Bash Question

Check if tomcat is running via shell script

I need to check if the tomcat is running in my system via a shell script. If not i need to catch the process id and kill tomcat. How shall it be achieved ? any help would be greatly appreciated.


in order to get the running process, I've used this command:

ps x | grep [full_path_to_tomcat] | grep -v grep | cut -d ' ' -f 1

You have to be careful, though. It works on my setup, but it may not run everywhere... I have two installations of tomcat, one is /usr/local/tomcat on port 8080 and /usr/local/tomcat_8081 on port 8081. I have to use '/usr/local/tomcat/' (with the final slash) as the full_path because otherwise it would return 2 different pids if tomcat_8081 is running as well.

Here's the explanation of what this command does:

1) ps x gives you a list of running processes ordered by pid, tty, stat, time running and command.

2) Applying grep [full_path_to_tomcat] to it will find the pattern [full_path_to_tomcat] within that list. For instance, running ps x | grep /usr/local/tomcat/ might get you the following:

13277 ?        Sl     7:13 /usr/local/java/bin/java -Djava.util.logging.config.fil
e=/usr/local/tomcat/conf/ [...] -Dcatalina.home=/usr/local/tomca
t [...]
21149 pts/0    S+     0:00 grep /usr/local/tomcat/

3) As we get 2 entries instead of one due to the grep /usr/local/tomcat/ matching the pattern, let's remove it. -v is the invert-match flag for grep, meaning it will select only lines that do not match the pattern. So, in the previous example, using ps -x | grep /usr/local/tomcat/ | grep -v grep will return:

13277 ?        Sl     7:13 /usr/local/java/bin/java -Djava.util.logging.config.fil
e=/usr/local/tomcat/conf/ [...] -Dcatalina.home=/usr/local/tomca
t [...]

4) Cool, now we have the pid we need. Still, we need to strip all the rest. In order to do that, let's use cut. This command removes sections from a FILE or a standard output. The -d option is the delimiter and the -f is the field you need. Great. So we can use a space (' ') as a delimiter, and get the first field, which corresponds to the pid. Running ps x | grep /usr/local/tomcat/ | grep -v grep | cut -d ' ' -f 1 will return:


Which is what you need. To use it in your script, it's simple:

pid=$(px x | grep "${tomcat_path}" | grep -v grep | cut -d ' ' -f 1)
if [ "${pid}" ]; then
  eval "kill ${pid}"