IS_EV
IS_EV

Reputation: 1048

Issue with setting environment variable through bat file to execute a java program

I have a batch file for setting up the environment variables as follows

 @echo off

echo -- Setting Environment variables --
set "TH=D:\apache-tomcat-7.0.37\";
set "WEB-INF=%TH%webapps\ROOT\WEB-INF";
set "CLASSES_HOME=%WEB-INF%\classes";
set "CONFIG=%WEB-INF%\config-files";
set "JARS=%TH%webapps\ROOT\WEB-INF\lib";
set "JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45";
set "_JAVA_OPTIONS=-Djava.net.preferIPv4Stack=true";
set "path=%path%;%JAVA_HOME%\bin;%WEB-INF%;%JARS%\jacob";

 setLocal EnableDelayedExpansion
 set "CLASSPATH=.;C:\WINNT\system32;%CLASSES_HOME%;%CONFIG%";
 for %%a in ("%TH%lib\*.jar") do (
   set CLASSPATH=!CLASSPATH!;%%a
 )

 for %%a in ("%CONFIG%\*.lic") do (
   set CLASSPATH=!CLASSPATH!;%%a
 )

  for %%a in ("%JARS%\*.jar") do (
   set CLASSPATH=!CLASSPATH!;%%a
 )

set CLASSPATH=!CLASSPATH!

echo %CLASSPATH%
echo %path%

Now I have a second batch file which invokes the first batch file to set up the environment variables and then a java class as follows

call D:\myFolder\setEnvironmentvaribales.bat
java -Xms256m -Xmx1024m com.myproject.java.runBatchToDelete

This is throwing an exception stating that main method cannot be found. I know for a fact that there is no issue with the java class as I can run this program directly. I believe for some reason the classpath and path setting in the setEnvironmentvaribales.bat is not getting set properly. Any help to resolve the issue would be greatly appreciated.

Upvotes: 1

Views: 2009

Answers (2)

ajb
ajb

Reputation: 31689

I've been trying this, and for some reason it appears that the EnableDelayedExpansion somehow interferes with the ability to set environment variables that will then be visible after the batch file is done. Your batch file says echo %CLASSPATH%. Try putting echo %CLASSPATH% after the call in your second batch file. If the output is different, you might be hitting the same problem I ran into.

The only thing I could get to work: At the end of setEnvironmentVariables.bat (or setEnvironmentVaribales.bat), add

echo set CLASSPATH=%CLASSPATH% > sometemporary.bat

and then, in the second batch file, after the call,

call sometemporary.bat

This seems to work. You should probably add a command to delete the temporary file.

P.S. The line toward the end

set CLASSPATH=!CLASSPATH!

is probably redundant. It looks like maybe you were trying to find a way to get the variable set for use by the other script, but it doesn't seem to work.

PPS. OK, Aacini's answer works a lot better.

Upvotes: 1

Aacini
Aacini

Reputation: 67206

Change this line:

set CLASSPATH=!CLASSPATH!

by this one:

endlocal & set CLASSPATH=%CLASSPATH%

Upvotes: 2

Related Questions