A Linux shell script to compile Java source code files that require building a CLASSPATH

Can you share an example of a Unix/Linux shell script that I can use to dynamically create a CLASSPATH so I can compile my Java source code files, where those files depend on JAR files?

Introduction to the solution

From time to time circumstances come up where I don't have Ant or an Ant-based project to compile my Java programs. On those occasions (which are very rare these days), I typically use a Linux shell script to compile my Java classes. I thought I'd share this "java compile" shell script here today.

The really nice thing this script does for you is to dynamically include all of the Jar files you need into your classpath. So, if your Jar files are all where they should be, compiling from the command line is a breeze.

The program makes two assumptions:

  1. You are in a directory above a directory named "src", and src contains your ".java" files.
  2. You are in a directory above a directory named "lib", and any Jar files that your program needs are in that directory.

My Java compile shell script

Because this fits my standard build directory structure, this works for me all the time.

Here is the script:

#!/bin/sh

THE_CLASSPATH=
PROGRAM_NAME=MainProgram.java
cd src
for i in `ls ../lib/*.jar`
    do
    THE_CLASSPATH=${THE_CLASSPATH}:${i}
done

javac -classpath ".:${THE_CLASSPATH}" $PROGRAM_NAME

if [ $? -eq 0 ]
then
    echo "compile worked!"
fi

Note that you will want to change the value of the variable PROGRAM_NAME to the name of your Java class file that contains the main method for your app.

Java compile shell script

I hope this Java compile shell script will come in handy on those times when you don't want or need to use Ant to compile your Java programs. Again, this should be pretty rare, but when you need a shell script like this, I hope this helps.