Celeb Glow
news | March 14, 2026

Why is the "set /p"-method used in a batch script to read the first line of a text file not working in the body of a "for"-loop?

I tried to apply the answer given by Spaceballs to this question within the body of a for-loop.

example.bat:

@echo off
copy NUL %1
echo firstLine >> %1
echo /=======================/
for /l %%x in (1,1,3) do ( echo %%x set /p A=< %1 echo %A%
)
echo /=======================/
set /p A=< %1
echo %A%

Result of start example.bat temp.txt:

 1 file(s) copied.

/=======================/

1

ECHO is OFF.

2

ECHO is OFF.

3

ECHO is OFF.

/=======================/

firstLine

Why is set /p A=< %1 not working in the body of the for-loop?

1 Answer

The main problem is that, apart from the loop variable, cmd expands variables in a batch file loop before the loop is executed, so, although A is being set within the loop, the value echoed is that prior to entry to the loop (ie blank). You can see that the value has been set by omitting the set before the final echo: the output will be the same.

The answer is to enable Delayed Expansion and use !A! instead of %A%.

By the way the copy and echo commands at the beginning of the file are an unnecessarily long way of writing echo firstLine > %1.

So your batch file will work as expected if you modify it as follows:-

@echo off
SetLocal EnableDelayedExpansion
rem copy NUL %1
rem echo firstLine >> %1
echo firstLine > %1
echo /=======================/
for /l %%x in (1,1,3) do ( echo %%x set /p A=< %1 echo !A!
)
echo /=======================/
rem set /p A=< %1
echo %A%

Note that you will be setting A to the same value in each pass of the loop. You will need to use a different technique if you want want each pass to show successive lines from the file.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy