2

I wrote a simple Linux Script this way

export JAVA_HOME=/usr/local/jdk1.6.0_20
export PATH=/usr/local/jdk1.6.0_20/bin
LIB_DIR=/home/praveen/lib

export CLASSPATH=.:$LIB_DIR/commons-logging-1.0.4.jar:$LIB_DIR/log4j-1.2.8.jar

 java -cp $CLASSPATH com.test.Sample

===============================================================================

The above script was working fine .

But when i tried for the first time with this , it was giving an error

export JAVA_HOME=/usr/local/jdk1.6.0_20
export PATH=/usr/local/jdk1.6.0_20/bin
export CLASSPATH = /home/praveen/lib/commons-logging-1.0.4.jar: /home/praveen/lib/log4j-1.2.8.jar

  java -cp $CLASSPATH com.test.Sample

As you can observe the only difference between these two scripts is that , in the below script on to the class path , i am not including the current directory path ( .)

Please let me know , why this will not work this way ??

Pawan
  • 31,545
  • 102
  • 256
  • 434
  • What error do you get? And where do you run this script from, are there are any class or JAR files present in the same directory from where you are running the script? – Jugal Shah Mar 12 '12 at 09:44
  • Related: [Using bash, how do you make a classpath out of all files in a directory](http://stackoverflow.com/q/4729863/320399) – blong Jul 30 '14 at 13:18

3 Answers3

7

You need to use:

export CLASSPATH=/home/praveen/lib/commons-logging-1.0.4.jar:/home/praveen/lib/log4j-1.2.8.jar

rather than:

export CLASSPATH = /home/praveen/lib/commons-logging-1.0.4.jar: /home/praveen/lib/log4j-1.2.8.jar

You can't put spaces in between the variable name and the equals sign in shell scripting.

Leonard Garvey
  • 1,517
  • 12
  • 8
2

You should not put any spaces in when you are setting variable, not even spaces around '=', it should be:

export CLASSPATH=/home/praveen/lib/commons-logging-1.0.4.jar:/home/praveen/lib/log4j-1.2.8.jar

If you have spaces in one of the elements use single or double quotations e.g.:

MY_VAR1=' variable with spaces'
MY_VAR2=variable_without_spaces
export MY_VAR3="${MY_VAR1}${MY_VAR2}"
sirgeorge
  • 6,331
  • 1
  • 28
  • 33
-2

Try this one..:

#!/bin/bash
export JAVA_HOME=...

cp=$(find lib -name "*.jar" -exec printf :{} ';')
if [[ -n "$CLASSPATH" ]]; then
    cp="$cp;CLASSPATH"
fi

"$JAVA_HOME/bin/java" -classpath "$cp" ...