A Unix shell script I use for compiling Java programs

By Alvin J. Alexander, devdaily.com

Here's a little shell script I use on one of our Linux servers to compile Java programs. 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.

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.


devdaily logo