views:

103

answers:

2

Hi everyone,

I have a java application launched by a .cmd file. I want to set the classpath of the application through this batch, all the needed jars are into a lib folder.

Here is what I tried :

 set _classpath=.
for %%i in (%1/lib/*.*) do ( set _classpath=%_classpath%;%%i )

Surprisingly, it seems that it does not act as expected. Let's say there is 3 jar in the lib folder :

  • pikachu.jar
  • sonic.jar
  • mario.jar

Here is what happens :

  1. set _classpath=.
  2. set _classpath=.;pikachu.jar
  3. set _classpath=.;sonic.jar
  4. set _classpath=.;mario.jar

Obviously, what I am looking to get is

  • set _classpath=.;pikachu.jar;sonic.jar;mario.jar

Any idea ?

Thanks and regards,

+1  A: 

CMD.EXE is expanding the %...% before running the loop.

You need delayed variable expansion, this is explained in set /? from a command prompt.

Richard
+3  A: 

Place this at the top of your batch file:

setlocal enabledelayedexpansion

Then inside the for loop, replace %_classpath% with !_classpath!

Without delayed expansion enabled, %_classpath% gets expanded once, at the beginning of your for loop.


[Edit] In response to a comment, here is a full code-listing

@echo off
setlocal enabledelayedexpansion

set _classpath=.
for %%i in (%1/lib/*.*) do (
    set _classpath=!_classpath!;%%i
)

echo %_classpath%
pause
BlueRaja - Danny Pflughoeft
Thanks BlueRaja (Thanks Richard as well.), there is another issue coming up when using this approach. I can see that the classpath looks something similar to that at the end of the loop :.;pikachu.jar ;sonic.jar ;mario.jar The spaces are inexpected and will hurt. Do you know a quick way to get rid of them ? I suppose we could do a right trim on %%i ?
Farid
@Farid: It's because you have a space at the end of your block. See edited answer.
BlueRaja - Danny Pflughoeft
Thanks very much !
Farid