0

I'm writing a simple bash script to shutdown tomcat, and if it doesn't stop gracefully then check if the tomcat's PID still exists and kill it.

I pass the tomcat name as a variable to the script as below. In some instances I pass two or three names of tomcat, which is why the use of FOR LOOP below

./shutdown.sh tomcat1

Content of the Shutdown.sh script

#!/bin/bash
for name in "$@"
do
    bash /opt/$name/bin/shutdown.sh   
done

sleep 30

for name in "$@"
do
   process_id=`ps -ef | grep $name | grep -v grep | awk '{ print $2 }'`

   if [ $process_id ] 
   then
       kill -9 $process_id
   fi

done

echo " Script Execution completed"

When tomcat shutdowns gracefully there is no issue. But when tomcat doesn't stop, I'm having issues.

Below peice of code when ran directly on command prompt gives me the correct process ID(62457) of tomcat. But the same peice of in shell script is giving me three process ID's(62610,62611,62457).

process_id=`ps -ef | grep $name | grep -v grep | awk '{ print $2 }'`

can you let me know why I'm getting three process ID's in the script compared to just one ?

Any other easier suggestion to KILL ?

Raj K
  • 1
  • 1
  • Instead of looping through possible PID's why don't you just pipe the results into `xargs kill -9`? IE: `ps -ef | grep $name | grep -v grep | awk '{ print $2 }' | xargs kill -9` – Josh Zhang Aug 06 '21 at 20:15
  • I haven't tested it yet, but wondering. In scenario where tomcat shutdown gracefully and there is no PID to KILL, basically no input to "xargs" command. will the xargs command complain of the syntax error ? – Raj K Aug 06 '21 at 20:22
  • If there is no PID's for `xargs kill -9` you will actually just get an error from `kill` since it would be the same as running the command without any PID's. – Josh Zhang Aug 06 '21 at 20:26
  • 1
    Your process_id command will include the `./shutdown.sh` command itself. You could add another grep in the pipeline like `. . .| grep -v shutdown.sh | grep -v grep . . .` or do something like ` . . . | egrep -v 'grep|shutdown.sh' . . .` – Brandon Xavier Aug 06 '21 at 21:11
  • Does your operating system have a generic init script or service manager system? Properly doing it in shell is not as trivial as it seems. – John Mahowald Aug 06 '21 at 23:50
  • @BrandonXavier ` | grep -v shutdown.sh | grep -v grep ` worked. Thank you. – Raj K Aug 09 '21 at 00:34
  • If you set `CATALINA_PID` when starting Tomcat, then `shutdown.sh 30 -force` does exactly the same thing as your script (but more properly). Cf. the [source code](https://github.com/apache/tomcat/blob/76da8deac37071e8a891580d74ba1322c7a2da2c/bin/catalina.sh#L482). – Piotr P. Karwasz Aug 09 '21 at 05:32

0 Answers0