0

I am trying to compose the classpath for a subsequent java -cp %jarlist% command. For that I need to concatenate the names of all *.jar files in a subdirectory lib.

This is what I came up with so far:

SET jarlist=
FOR %%f IN ("lib\*.jar") DO SET jarlist=%jarlist%;%%f

echo jarlist='%jarlist%'

... but for some reason the strings are not concatenated! At the end the jarlist-variable contains only the name of the last .jar found, e.g. jarlist=';lib\slf4j-all.jar'

If I - instead of concatenating them - echo the individual substrings inside the loop then the individual values look correct:

FOR %%f IN ("lib\*.jar") DO echo %%f

For some reason the concatenation, i.e. the SET jarlist=%jarlist%;%%f does not work inside the loop. Why? How can I concatenate all the values into one string (separated by ';')?

mmo
  • 3,897
  • 11
  • 42
  • 63
  • 5
    This is one of those hard concepts for people to understand with Batch Files. You will need to enable delayed expansion with the `SETLOCAL` command and then reference your variables with exclamation points instead of percent symbols. – Squashman Nov 15 '21 at 22:55
  • 1
    How this can be done is explained by the usage help output on running `set /?` in a command prompt. There is explained when and how to use [delayed expansion](https://ss64.com/nt/delayedexpansion.html) on an __IF__ and a __FOR__ example. The __FOR__ example is nearly the code you need for this task. See for example [How to concatenate all directory paths inside a text file to a semicolon separated list assigned to an environment variable?](https://stackoverflow.com/a/69956519/3074564) (Same method for directory paths read from text file instead of file names from file system.) – Mofi Nov 16 '21 at 18:02
  • Thanks all for responding and sorry that I reiterated an apparently old issue. I *had* googled but obviously wasn't successful. Using the `setlocal EnableDelayedExpansion` and `FOR %%f IN ("lib\*.jar") DO SET jarlist=!jarlist!;%%f` this finally worked like a charm! Thanks again! – mmo Nov 17 '21 at 20:31

0 Answers0