Variable with value less than 10 placing before the redirection symbol

Tag(s):

Variable with value less than 10 placing before the redirection symbol(>>) is causing issue. That is because the end result looks like this: 1>>, 2>>, etc. Here is a good example illustrating the issue:

@ECHO OFF
SET i=1
SET filename=output.txt
del /q %filename%
 
FOR /L %%V IN (1,1,5) DO (
CALL :Increment
)
GOTO :EOF
 
:Increment
  REM Issue: "ECHO is off." is being redirected to your file.
  ECHO %i%>>%filename%
  SET /a i+=1
  GOTO :EOF

To resolve this issue, you have to escape your variable with ^. Here is the correct code.

@ECHO OFF
SET i=1
SET filename=output.txt
del /q %filename%
 
FOR /L %%V IN (1,1,5) DO (
CALL :Increment
)
GOTO :EOF
 
:Increment
  REM To resolve the issue. Escape the index or count with ^
  ECHO ^%i%>>%filename%
  SET /a i+=1
  GOTO :EOF