0

I was bored so I tried writing simple code that generates a text document with a list of numbers starting from 1 and counts forever. This code here says "Echo is OFF" on the first line, "10" on the second line, "11" on the third, and so on. Why does it say "echo is off" and why doesn't it start counting from one? Thanks.

set number=0
echo %number%>numberlist.txt
goto countloop

:countloop
cls
echo The current number is %number%
set /a number=%number%+1
echo %number%>>numberlist.txt
goto countloop

2 Answers 2

2

NICE :) When %number% is 0-9 preceding the > or >> it is intepreted to be a stream number. So when %number% is 0 you are echoing to STDIN... which amounts to ECHO which displays the ECHO state. You won't start echoing to the file until %number% is something other than a single digit (no longer intepreted as a stream.. STDIN, STDOUT, STDERR...). Try doing it like this:

@echo off
set /a number=0
set MyFile=numberlist.txt
if exist "%MyFile%" del /y "%MyFile%"

:countloop
echo The current number is %number%
set /a number+=1
echo.%number%>>"%MyFile%"
goto countloop​

For this reason... and the possibility that the echoed varaible could be undefined I never use ECHO followed by a space. I always use ECHO( or ECHO. Purists prefer ECHO( but beginners tend to get confused and think there are mismatched parens.

Sign up to request clarification or add additional context in comments.

Comments

1

As RGuggisberg said, single digit numbers are interpreted to mean file handles (or streams), with 0 being stdin, 1 stdout, 2 stderr. and 3-9 undefined.

echo.%number%>>%MyFile% will work, but it is not a general solution.
Something like echo.Test %number%>>%MyFile% will fail as before.

The simplest general solution is to move the redirection before the command.

>>%MyFile% echo %number%

Other options are to put parentheses around the command:

(echo %number%)>>%MyFile%

Or to escape the number:

echo ^%number%>>%MyFile%

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.