I'm quite sure the batch code in question is not complete or reduced to a script code not really suitable to reproduce the problem because with Device.json
existing in folder Desktop
and no other Device*.json
file existing, the empty line is first written to Device1.json
. A file with name Device.json
is never overwritten by the batch code in question because variable FileNumber
has always at least the value 1
.
Well, the FOR option /F
is most likely wrong here as I suppose the FOR loop should search for *.json files as done without /F
. Using a wildcard pattern like *.json together with option/F
results in error message:
The system cannot find the file *.json.
Run in a command prompt window for /?
or help for
for help on syntax of this command.
It is completely unclear what is the purpose of the FOR loop because the FileName
variable is not used at all. This variable should perhaps hold the name of last found *.json if there was any *.json file found at all. But that also does not make sense if not further used anywhere.
It is also unclear why BaseName
and FileNumber
are defined inside the loop and not outside.
In the complete batch code the label FileNameLoop
is perhaps the beginning of a subroutine. But in the reduced batch code in question there is no call :FileNameLoop "%%G"
which I would expect in this case.
So the question is hard to answer as it is unclear what is really the problem with posted batch code.
:MainProcessNew
cd /D "%USERPROFILE%\Desktop"
rem Useless FOR loop without /F commented out.
rem for %%G in (*.json) do set "FileName=%%G"
set "BaseName=Device"
set "FileNumber="
rem Skip searching for files with a file number
rem after Device if there is no Device.json file.
if not exist "%BaseName%.json" goto CreateFile
rem Otherwise keep Device.json as is and search for Device1.json,
rem Device2.json, ... until a Device*.json file with current number
rem is not found and use this number for next Device*.json file.
set "FileNumber=0"
:FileNameLoop
set /A FileNumber+=1
if exist "%BaseName%%FileNumber%.json" goto FileNameLoop
:CreateFile
rem Note: FileNumber is replaced in the line below by an empty
rem string if there is no Device.json in desktop folder.
echo.>"%USERPROFILE%\Desktop\%BaseName%%FileNumber%.json"
Hint: For debugging a batch file
- comment out or remove all
@echo off
or echo off
in the batch file or change off
to on
,
- open a command prompt window,
- enter
"Path to batch file\BachFileName.bat"
and press RETURN.
Now it can be seen in the command prompt window each line executed by Windows command processor after preprocessing each line and each command block which means after replacing all %VariableName%
by the current value of the variable in current line or entire command block.
And error messages can be also seen as the command prompt window remains open after processing batch file stopped, except it contains the command exit
without option /B
which always terminates the current command process.