Dynamic Java classpath - build your classpath in a shell script

Here's a Bourne Shell script I use to run a Java anti-spam program I wrote. The program I'm running isn't important, but what is worth sharing about this shell script is how I dynamically build the Java CLASSPATH by including all of the jar files in the lib directory.

Other parts of the shell script (showing a shell script for loop) may be worth sharing as well, but I think that building the Java classpath dynamically in the shell script is probably the most important part.

With that being said, here's the shell 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 Linux 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.

 

Thanks

It worked just fine.
Found using google
http://www.google.com/search?hl=en&q=classpath+shell+for&btnG=Search

Easier using "$*" and IFS

set lib/*.jar
CLASSPATH=$(IFS=:; echo "$*")
export CLASSPATH

Using a subshell "$()" preserves the original value of IFS.

When I try that, and echo the

When I try that, and echo the CLASSPATH (instead of exporting it), the output I get is "lib/*.jar". I don't know if that will work.

Might be a bash v. sh thing

Works from Bash. You could try it w/ dash for stricter Bourne shell behavor, or just 1s/sh/bash/.

$ ls lib/*.jar
lib/junit.jar      lib/mssql_jdbc.jar   lib/oro_regexp.jar
lib/libraries.jar  lib/oracle_jdbc.jar  lib/protomatter-1.1.2.jar
$ set lib/*.jar
$ CLASSPATH=$(IFS=:; echo "$*")
$ export CLASSPATH
$ declare -p CLASSPATH
declare -x CLASSPATH="lib/junit.jar:lib/libraries.jar:lib/mssql_jdbc.jar:lib/oracle_jdbc.jar:lib/oro_regexp.jar:lib/protomatter-1.1.2.jar"

IFS works fine

Sorry, I have no idea what I did the other day, but as I just tested this again with the Bourne shell and Bash, and it worked fine with both.
I created the following script:

set lib/*.jar
CLASSPATH=$(IFS=:; echo "$*")
echo $CLASSPATH

created a lib directory with a couple of fake jar files in it, ran it using the Bourne shell, and the output looked as desired:

$ sh classpath.sh
lib/a.jar:lib/b.jar:lib/c.jar

Thanks for your suggestion, and sorry again for my confusion. The IFS is a good technique, and I need to remember to use it more often.
 

Post new comment

The content of this field is kept private and will not be shown publicly.