Reputation: 11
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>
Upvotes: 1
Views: 143
Reputation: 6558
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.
Upvotes: 3