Your code is failing when the file already exists because you are setting a variable value and later accessing the value within the same parenthesized code block; %uses%
is expanded when the line is parsed, and the entire code block is parsed all at once. So the value you are echoing is the value that existed before the FOR loop is executed - not what you want.
You could solve the problem by enabling delayed expansion using setlocal enableDelayedExpansion
, and then using !uses!
instead of %uses%
. Type help set
from a command prompt for more information. Start reading with the paragraph that begins "Finally, support for delayed environment variable expansion has been added..." about halfway through the help.
But there is a simpler way that avoids the need for delayed expansion. You only need to set the value within the IF block. You can access it later outside of the IF block.
There is one other issue that you are currently avoiding, but you should be aware of: 1>filename
and >filename
do the same thing - they are an instruction to redirect standard output (stdout) to a file. 1 is the id of stdout, and it is the default when a number is not explicitly given. 2>filename
redirects standard errror (stderr) to a file. You are avoiding interpretation of the number as the stream id because you have a space between the number and the >
. But if you are not careful, you will someday not have a space and be confused as to why the number is not printing. You can avoid the problem by putting the redirection at the front instead of at the end. >filename echo %uses%
So here is a complete working solution.
@echo off
setlocal
if not exist statistic_files mkdir statistic_files
cd statistic_files
set "file=%username%-use_tracking"
set "uses=1"
if exist %file% for /f %%G IN (%file%) do set /A uses=%%G+1
>%file% echo %uses%