Why is an extra file being created in FOR loop of batch program?

前端 未结 3 1373
失恋的感觉
失恋的感觉 2020-12-19 19:30

I\'ve written the following batch file to create multiple files using FOR loop:

@echo off  
cls  
FOR /L %%i IN (1 1 10) DO (  
    echo.> file%%i.txt  
         


        
3条回答
  •  轮回少年
    2020-12-19 19:49

    Like adarshr said, the second FOR loop can find even the new created files.
    You can avoid this by using FOR/F with a command, as the result of the dir is completely fetched before the body of the loop is executed.

    ...
    FOR /F "delims=" %%i IN ('dir /b *.txt') DO (  
        echo.> file%%i.txt
        IF ERRORLEVEL 0 echo Successfully created file 'file%%i.txt'.  
    )
    

提交回复
热议问题