How to dynamically build a Java Classpath in a Bourne Shell script

By Alvin J. Alexander, devdaily.com

Here's a Bourne Shell script I use to run an anti-spam program I wrote. The thing I think that's worth sharing about this script is how I dynamically build the CLASSPATH by including all of the jar files in the lib directory. Other parts of the script may be worth sharing as well, but I think that's the most important part.

With that being said, here's the script:

#!/bin/sh

export JAVA_HOME=/usr/local/java
PATH=/usr/local/java/bin:${PATH}

cd /home/ala/DevDaily/Musubi

#---------------------------------#
# dynamically build the classpath #
#---------------------------------#
THE_CLASSPATH=
for i in `ls ./lib/*.jar`
do
  THE_CLASSPATH=${THE_CLASSPATH}:${i}
done

#---------------------------#
# run the anti-spam program #
#---------------------------#
java -cp ".:${THE_CLASSPATH}"  \
   EmailAgentController        \
   lib/mail.properties         \
   lib/userMail.properties     \
   message.uid.cache           \
   | tee -a SPAM.mbox

I guess the tee command and the line continuation stuff is good too, if you've never seen that. Bourne Shell programming -- heck, programming on a Unix system -- is pretty cool.


devdaily logo