For loop local variable

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Werseree
Posts: 1
Joined: 26 Jul 2014 17:16

For loop local variable

#1 Post by Werseree » 26 Jul 2014 17:27

I'm hoping someone can help me understand this weirdness. If I do...

Code: Select all

for /f "delims=" %%i in (some_file.txt) do (
    echo %%i
)


Then each line of the file is echoed out. OK, so far so good. But if I make this ever so small change...

Code: Select all

for /f "delims=" %%i in (some_file.txt) do (
    set "line=%%i"
    echo %line%
)


Then it doesn't at all behave like I would expect. I would expect that at each iteration of the loop, the variable "line" would be set to the current line of text, then echo would of course echo that line. But what actually happens is that the echo statement is always ever printing the *last* line of the file, over and over, for every iteration. Why...?! This behavior doesn't make any sense to me. Can someone help me out?

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: For loop local variable

#2 Post by Squashman » 26 Jul 2014 19:22

You need to use delayed expansion.

Code: Select all

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%i in (some_file.txt) do (
    set "line=%%i"
    echo !line!
)

Post Reply