Search code examples
batch-fileif-statementfor-loopdosbreak

How to break out of for-loop using condition statement in batch file?


I am doing some processing of a large number of files, and I want to limit what I'm doing to the first 9 files found. I have tried this in a batch file and it does not work. It processes for all the files, and does not stop at the 9th one. What have I done wrong?

setlocal
set fileCount=0

for %%I in (*.doc) do (
  rem do stuff here ...
  set /a fileCount+=1
  if "%fileCount%"=="9" exit
)

Solution

  • The problem is that %fileCount% is being expanded during parse-time rather than during execution-time, so it doesn't take into account the changes to fileCount during the course of execution. So your for-loop is equivalent to this:

    for %%I in (*.doc) do (
      rem do stuff here ...
      set /a fileCount+=1
      if "0"=="9" exit
    )
    

    To correct it, you need to enable and use delayed expansion. You do that by using setlocal EnableDelayedExpansion rather than merely setlocal, and !fileCount! rather than %fileCount%. So:

    setlocal EnableDelayedExpansion
    set fileCount=0
    
    for %%I in (*.doc) do (
      rem do stuff here ...
      set /a fileCount+=1
      if "!fileCount!"=="9" exit
    )
    

    For more information, see http://ss64.com/nt/delayedexpansion.html.