# Windows command line: How to append a variable in a loop?

I'm trying to fill a variable with a space-separated list of files, but I can't quite seem to get my head around it.

Here's what I have so far:

set js_files=
for %%f in (js/*.js) do set js_files=%js_files% js/%%f
echo %js_files%
C:\path\to\jsminifier.exe --inputfiles %js_files%


I would have expected this to keep appending the js_files variable with the next filename, but instead it replaces the whole variable:

c:\dir>script.cmd
c:\dir>set js_files=
c:\dir>for %f in (js/*.js) do set js_files= js/%f
c:\dir>set js_files= js/one.js
c:\dir>set js_files= js/two.js
c:\dir>set js_files= js/three.js
c:\dir>echo  js/three.js
js/three.js


I see in the second line of output that the whole for line seems to be parsed before execution, so the (initial) empty variable value is used for all iterations.

Does anyone know how to properly append to the variable?

Thanks!

-

Try changing it to this:

set js_files=
for %%f in (js/*.js) do set js_files=!js_files! js/%%f
echo %js_files%
C:\path\to\jsminifier.exe --inputfiles %js_files%


Note the change of set js_files=%js_files% js/%%f to set js_files=!js_files! js/%%f – by using the exclamation points in place of percent signs, you're instructing the shell to expand the environment variable dynamically during execution.

-
@Randolf - not really working ... on which Windows version does it work for you? –  RonK May 25 '11 at 7:08
@RonK: I used this technique on Windows 7 (64-bit Edition) for some other project a few months ago. –  Randolf Richardson May 25 '11 at 7:10
@RonK: Oh, I see what's missing -- you'll need to start Cmd with the /V:ON command-line switch first. Once you do this, then run the batch file, the "delayed environment" feature will work. –  Randolf Richardson May 25 '11 at 7:14
@RonK: Instead of using the /V:ON switch, just insert this line (two words) at the beginning of your batch file (it will be a lot easier): Setlocal EnableDelayedExpansion –  Randolf Richardson May 25 '11 at 7:17
Adding setlocal EnableDelayedExpansion and changing to exclamation marks worked. Thanks! –  Alan May 27 '11 at 4:06