Take the 2-minute tour ×

I understand the command would be javac file_name.java but how would I put together a shell script which could compile several java files?

I was also thinking about copying the files, which I presume I just use cp and absolute file path referencing.

share|improve this question
The usual way is to use a build tool like make or ant. –  Mechanical snail Aug 18 '12 at 21:16
Yes sorry, javac –  peroni_santo Aug 18 '12 at 21:19
Why do not you use maven? (maven.apache.org) –  Alexandre Dupriez Aug 18 '12 at 21:41
add comment

2 Answers

up vote 1 down vote accepted

Create a .sh file and add the following contents. Make the file as executable and run it. (Specify the complete path along with the file name)

#! /bin/sh
javac sample.java
share|improve this answer
This will recompile every script each time called, which is less than efficient. –  Ignacio Vazquez-Abrams Aug 18 '12 at 21:18
If I wanted to copy my java file into the location where javac is located, how do I make sure each time I copy my java file it overwrites the previous version? Is there an argument for the cp command? –  peroni_santo Aug 18 '12 at 21:20
cp will overwrite if file exists. And Why do you want to copy the file to your javac location. just add the java/bin to your environment and you can use javac anywhere. –  Akhil Dev Aug 18 '12 at 21:25
@AkhilDev I am a bit of a newbie to Unix, can you please explain how I do this? Thanks –  peroni_santo Aug 18 '12 at 21:44
add comment

Try this script: compile_java_files.sh


typeset -r JAVA_FILES_DIR=$(cd full_path_to_java_files 2>/dev/null ; pwd)   # JAVA FILES DIRECTORY

LOG_DIR="/tmp/java_compilation/logs"    # Create this dir or use another one

for java_file in `ls $JAVA_FILES_DIR`;
    javac $java_file
    return_status=`echo $?`
    if [ $return_status -ne 0 ]
        echo "Failed to compile $java_file" >> $LOG_DIR/$java_file.ERR

        exit 1

Then run your script(don't forget to specify the path to the directory that contain java files):

chmod +x compile_java_files.sh
share|improve this answer
add comment

Your Answer


