Cleanup and server restart script I have written a simple script for managing our Tomcat and Apache instances for deployment. What this script basically does is, when called, it copies the ROOT.war from its pwd and pushes them to two Tomcat instances. Before that, it removes the old ROOT.war file and ROOT folder, restarts them, cleans the log files, restarts both Tomcat instances and Apache webserver (load-balancer and failover guy).

I have just pasted commands in a script and thought would learn more about it when I optimize this script, such as adding checks.

#!/bin/bash
sh /home/deploy/tomcatfirst/bin/catalina.sh stop
rm -rf /home/deploy/tomcatfirst/webapps/ROOT/
rm -rf /home/deploy/tomcatfirst/logs/
rm /home/deploy/tomcatfirst/webapps/ROOT.war
cp ROOT.war /home/deploy/tomcatfirst/webapps/
mkdir /home/deploy/tomcatfirst/logs


sh /home/deploy/tomcatfirst/bin/catalina.sh stop
rm -rf /home/deploy/tomcatsecond/webapps/ROOT/
rm /home/deploy/tomcatsecond/webapps/ROOT.war
rm -rf /home/deploy/tomcatsecond/logs/
mv ROOT.war /home/deploy/tomcatsecond/webapps/
mkdir /home/deploy/tomcatsecond/logs

sh /home/deploy/tomcatfirst/bin/catalina.sh start
sh /home/deploy/tomcatsecond/bin/catalina.sh start
service apache2 restart
Adding checks? Just specify

set -e


at the beginning of the script. Should any command fail, the script will stop running, instead of wreaking more damage.

Using variables for repeated paths might make the script more readable.

tomcat1=/home/deploy/tomcatfirst
tomcat2=/home/deploy/tomcatsecond

sh "$tomcat1"/bin/catalina.sh stop


(BTW, shouldn't the second stop use $tomcat2?)

Once you have them, changing the above line to

set -eu


might be another improvement - the script will fail if a variable is not defined, which can happen if you mistype its name.

As the commands for both the server are the same, you can wrap them in a loop:

for tomcat /home/deploy/tomcat{first,second} ; do
    sh "$tomcat"/bin/catalina.sh stop
    # ...
done


If the servers are critical, you should specify the commands with full paths (e.g. /bin/mkdir).