سؤال

I have a for loop using find string searching for a certain string in a log, but it doesn't work correctly. It does everything in errorlevel 0 even though there's no such trace of it in the log.

@Echo on

for /L %%x in (1, 1, 1000) do (
findstr /N /I /C:"MapException: Key '%%x'" "C:\Program Files (x86)\Steam\SteamApps\common\Starbound\starbound_server.log"
if %errorlevel%==0 (
    Echo Memory Error at MapException: Key '%%x'!
)
)
pause

I was wondering what's going on with it?

هل كانت مفيدة؟

المحلول

@Echo on
for /L %%x in (1, 1, 1000) do (
    findstr /N /I /C:"MapException: Key '%%x'" "C:\Program Files (x86)\Steam\SteamApps\common\Starbound\starbound_server.log"
    if not errorlevel 1 (
        Echo Memory Error at MapException: Key '%%x'!
    )
)
pause

Why? Well, try it this two lines

(( echo hi | find "k" ) & echo %errorlevel% )
(( echo hi | find "k" ) & if errorlevel 1 echo not found )

The "problem" is the expansion of variables inside block (the lines enclosed in parenthesis). When the execution reaches a block, all variable reads inside them are replaced with the values of the variables before the block start to execute. When the block executes, variables can change its values, but this changes are not seen inside the block as they were replaced with its values.

How to solve it?

Enable delayed expansion and use the sintax !errorlevel!. So, variable reads gets no replaced with variable values at block parse time. The changes in variables inside the block are visible inside the block.

Or, in this case, as the variable involved is errorlevel, use the classic if form of checking its value.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top