Simple script to compile and execute a Java application with any number of parameters

  • e.g. ./BashJavaExecutor.sh MyApp.java
  • e.g. ./BashJavaExecutor.sh MyApp.java “arg1” “arg2” 33
JAVA=$JAVA_HOME/bin/java
JAVAC=$JAVA_HOME/bin/javac
JAVA_HEAP_MAX=-Xmx1024m
CLASSPATH=${CLASSPATH}

args=("$@")

#Remove old class files (suppress warning for DNE)
rm ${args[0]}*.class 2> /dev/null

echo "Compiling Script ${args[0]}"
$JAVAC -classpath "$CLASSPATH" ${args[0]}.java

numOfArgs=${#args[@]}
arr=()
for (( c=1; c <= $numOfArgs; c++))
do
   let pos=$c-1
   arr[$pos]=${args[$c]}
done

$JAVA $JAVA_HEAP_MAX -classpath "$CLASSPATH" ${args[0]} ${arr[@]}