Search code examples
windowsfor-loopbatch-filecmdgoto

Batch file: GOTO in a FOR loop


I have a batch file with a FOR loop. In the loop I must wait for a process to end, for which I used IF and GOTO. The problem is the GOTO is breaking the loop. I tried to find other solutions but I didn't find anything. How can it be done?

@echo off
for /f "tokens=*" %%a in (file.txt) do (
bla bla bla
bla bla bla
:check
tasklist /FI "IMAGENAME eq prog.exe" 2>NUL | find /I /N "prog.exe">NUL
if "%ERRORLEVEL%"=="0" (goto check)
)

Solution

  • Inside the loop, you could use a call to a subroutine, there are gotos allowed.
    The loop will not be broken by a call to a subroutine.

    @echo off
    for /f "tokens=*" %%a in (file.txt) do (
      bla bla bla
      bla bla bla
      call :check
    )
    exit /b
    
    :check
    tasklist /FI "IMAGENAME eq prog.exe" 2>NUL | find /I /N "prog.exe">NUL
    if "%ERRORLEVEL%"=="0" (goto check)
    exit /b