How to build a dynamic Java classpath in a shell script

Here's a Bourne Shell (sh) 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:


export JAVA_HOME=/usr/local/java

cd /home/ala/DevDaily/Musubi

# dynamically build the classpath #
for i in `ls ./lib/*.jar`

# run the anti-spam program #
java -cp ".:${THE_CLASSPATH}"  \
   EmailAgentController        \
   lib/         \
   lib/     \
   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.



It worked just fine.
Found using google


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"

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 "$*")

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

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.

Add new comment

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

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.