Search code examples
batch-filefor-looperrorlevel

For loop does not throw errorlevel of 1 when folder is empty


I have the following line in a batch script

for %%a in (*.rmt) do (findstr /C:"        model='" %%a)>tmp.par

When I run this on an empty folder, the errorlevel is still 0.

However, if I replace *.rmt with a filename, say x.rmt, which doesnt exist in the folder either, the errorlevel becomes 1.

Ideally, if there are no RMT files in the folder, shouldnt the errorlevel!=0?

I require this For loop to work on *.rmt, as there might be 0 to multiple RMT files in a folder. Please help.

Thanks.

Note: If the string " model='" exists in one RMT file, it will compulsorily be present in all the other RMT files(if any) in the folder.


Solution

  • The findstr is never executed if there are no matches to the *.rmt, hence the errorlevel remains unchanged.

    When you use x.rmt, FOR changes behaviour - it's no longer looking for a filename matching, it's looking at a particular string - which may or may not be a filename, which may or may not exist.

    You could deliberately set errorlevel before the for

    @ECHO OFF
    SETLOCAL
    ECHO y|FIND "x">nul
    for %%a in (*.rmt) do (findstr /C:"        model='" %%a)
    ECHO errorlevel=%errorlevel%
    GOTO :EOF
    

    which will return errorlevel 1 unless the match is found.