Java compile example - A Linux shell script

A Java compile example: How to compile a Java program from a Unix/Linux shell script.

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:


cd src
for i in `ls ../lib/*.jar`

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

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

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.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.