Using "set" within a for loop?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gdiddy
Posts: 3
Joined: 28 Jan 2009 16:21

Using "set" within a for loop?

#1 Post by gdiddy » 28 Jan 2009 16:40

I'm utterly confused. "set" is acting very strangely within a for loop. Here's my code. PortList is a file with 4 lines of text.

Code: Select all

set count=1
for /f "tokens=1" %%i in (PortList) do (
echo %count%^) %%i
set /A count=%count%+1
)
echo.
set /P input=Please select [1-%count%]:


The output I EXPECT is

Code: Select all

1) [first entry in PortList]
2) [2nd entry]
3) [3rd entry]
4) [4th entry]

Please select [1-5]:


(yes, I know I need to decrement count before that last line, but I'll deal with that later).

What I get instead is

Code: Select all

1) [first entry in PortList]
1) [2nd entry]
1) [3rd entry]
1) [4th entry]

Please select [1-2]:


Notice that it DOES increment count at the end, so I get "1-2" instead of "1-1".

What am I missing?

gdiddy
Posts: 3
Joined: 28 Jan 2009 16:21

#2 Post by gdiddy » 29 Jan 2009 11:12

Nobody?

gdiddy
Posts: 3
Joined: 28 Jan 2009 16:21

#3 Post by gdiddy » 29 Jan 2009 13:13

In case anyone cares, the answer is delayed expansion.

Corrected code

Code: Select all

setlocal ENABLEDELAYEDEXPANSION
set count=1
for /f "tokens=1" %%i in (PortList) do (
echo !count!^) %%i
set /A count=!count!+1
)
set /A count=%count%-1
echo.
set /P input=Please select [1-%count%]:

faust
Posts: 2
Joined: 20 Feb 2009 22:36

#4 Post by faust » 27 Feb 2009 06:40

gdiddy wrote:In case anyone cares, the answer is delayed expansion.

Corrected code

Code: Select all

setlocal ENABLEDELAYEDEXPANSION
set count=1
for /f "tokens=1" %%i in (PortList) do (
echo !count!^) %%i
set /A count=!count!+1
)
set /A count=%count%-1
echo.
set /P input=Please select [1-%count%]:


You can save yourself the trouble of decrementing your counter with a little rearranging:

Code: Select all

setlocal ENABLEDELAYEDEXPANSION
set count=0
for /f "tokens=1" %%i in (PortList) do (
set /A count=!count!+1
echo !count!^) %%i
)
echo.
set /P input=Please select [1-%count%]:

Post Reply