1

In both cases the directory contains three files named test1.txt, test2.txt, test3.txt

Can someone explain why this works:

echo off
set CP=
for %%f in (*.txt) do (
    call :concat %%f
)
echo %CP%

:concat
set CP=%CP%;%1

output:

C:\test>test

C:\test>echo off
;test1.txt;test2.txt;test3.txt

C:\test>

But this does not:

echo off
set CP=
for %%f in (*.txt) do (
    set CP=set CP=%CP%;%%f
)
echo %CP%

output:

C:\test>test

C:\test>echo off
;test3.txt

C:\test>
1
  • 1
    Maybe, this can help Commented Jan 12, 2015 at 14:38

1 Answer 1

3

It has to do with Delayed Expansion.

For example, this will work just like your first example:

echo off
SETLOCAL EnableDelayedExpansion
set CP=
for %%f in (*.txt) do (
    set CP=!CP!;%%f
)
echo %CP%
ENDLOCAL

When Delayed Expansion is enabled then variables surrounded with ! are evaluated on each iteration instead of only the first time when the loop is parsed (which is how variables surrounded with % are parsed).

Your first example works because the processing is done in a CALL statement which passes control to another segment of the batch file which is technically outside the loop so it is parsed individually each time it is executed.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.