简体   繁体   中英

Windows 7 Batch File for loop

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM