我有一个使用查找字符串在日志中搜索某个字符串的for循环,但是它无法正常工作。即使日志中没有这样的痕迹,它也会执行错误级别0的所有操作。
@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
我想知道这是怎么回事?
@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
为什么?好吧,尝试这两行
(( echo hi | find "k" ) & echo %errorlevel% )
(( echo hi | find "k" ) & if errorlevel 1 echo not found )
“问题”是块内部变量的扩展(括号内的行)。当执行到达一个块时,在该块开始执行之前,将其中的所有变量读取都替换为变量的值。执行该块时,变量可以更改其值,但是在块内部看不到此更改,因为它们已被其值替换。
怎么解决呢?
启用延迟扩展并使用sintax !errorlevel!
。因此,在块解析时,变量读取不会被变量值替换。块内变量的更改在块内可见。
或者,在这种情况下,由于涉及的变量是errorlevel
,请使用经典if
形式来检查其值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句