Page 1 of 1

Using "set" within a for loop?

Posted: 28 Jan 2009 16:40
by gdiddy
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?

Posted: 29 Jan 2009 11:12
by gdiddy
Nobody?

Posted: 29 Jan 2009 13:13
by gdiddy
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%]:

Posted: 27 Feb 2009 06:40
by faust
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%]: