Dmi3
I need to check if the app exited gracefully, but it seems findstr and errorlevel do not work the way I need it. Here is what I have so far:
Code: Select all
if exist trail.txt.* (
FOR %%G IN (trail.txt.*) do (findstr /C:"!End of Trail File" "%%G")
if %ERRORLEVEL% GTR 0 (
echo Your previous session exited unexpectedly.
move %%G dbg_%%G
) else (
del /f /q %%G
)
)
Anybody have an example?
----------------------------
#2 03 Feb 2009 17:41
avery_larry
%errorlevel% works like any other standard variable. If you put it inside an if statement (or a for loop or other things), it's processed when the if command is called -- not inside the if (all variables inside the IF parentheses are evaluated when the IF is called -- not in the midst of the IF statement).
There are a variety of ways to fix this. Probably the best for what you're doing is to use the "if errorlevel" code instead of %errorlevel% like this:
Code: Select all
if exist trail.txt.* (
FOR %%G IN (trail.txt.*) do (findstr /C:"!End of Trail File" "%%G")
if errorlevel 1 (
echo Your previous session exited unexpectedly.
move %%G dbg_%%G
) else (
del /f /q %%G
)
)
Another possibility is to use delayedexpansion -- which means it waits as long as possible before evaluating a variable -- so instead of evaluating %errorlevel% when the if statement is called, it evaluates it when the nested if statement is called:
Code: Select all
setlocal enabledelayedexpansion
if exist trail.txt.* (
FOR %%G IN (trail.txt.*) do (findstr /C:"!End of Trail File" "%%G")
if !errorlevel! GTR 0 (
echo Your previous session exited unexpectedly.
move %%G dbg_%%G
) else (
del /f /q %%G
)
)
The final way to accomplish this is by calling a subroutine instead of keeping it all inside the if statement:
Code: Select all
if exist trail.txt.* call :subroutine
<other code here>
goto :eof
:subroutine
FOR %%G IN (trail.txt.*) do (findstr /C:"!End of Trail File" "%%G")
if %ERRORLEVEL% GTR 0 (
echo Your previous session exited unexpectedly.
move %%G dbg_%%G
) else (
del /f /q %%G
)
goto:eof
Code: Select all
if exist trail.txt.* (
FOR %%G IN (trail.txt.*) do (
findstr /C:"!End of Trail File" "%%G"
if %ERRORLEVEL% GTR 0 (
echo Your previous session exited unexpectedly.
move %%G dbg_%%G
) else (
del /f /q %%G
)
)
)
Code: Select all
if exist trail.txt.* (
FOR %%G IN (trail.txt.*) do (
findstr /C:"!End of Trail File" "%%G"
if errorlevel 1 (
echo Your previous session exited unexpectedly.
move %%G dbg_%%G
) else (
del /f /q %%G
)
)
)
So essentially IF ERRORLEVEL 1 is the same as IF %ERRORLEVEL% GEQ 1 only not restricted to obeying the rules of variables (when they're evaluated).
----------------------------
#3 05 Feb 2009 17:47
Dmi3
Thank you avery_larry!