views:

163

answers:

2

Hi All,

I have written following code

setlocal

set /A sample =1 

:first

type C:\test.txt | find "inserted"

if %ERRORLEVEL% EQU 0 goto test

if %ERRORLEVEL% EQU 1 goto exam

:test

echo "testloop" >> C:\testloop.txt

set /A sample = %sample% + 1 

if %sample% LEQ 4 goto first

:exam

echo "exam loop" >> C:\examloop.txt

endlocal

but it is going to lable "exam" even though error level is not equal to "1" plz help me

+2  A: 

You need to list the error levels in descending order (errorlevel2, errorlevel1, errorlevel0...).

See this explanation and example.

JRL
+2  A: 

Your problem isn't goto, its that errorlevel requires special treatment, it's not like an ordinary environment variable. The only test you can do with errorlevel is to test whether it is greater than or equal to value.

so you have to test errorlevel values from highest to lowest because if errorlevel 1 then if errorlevel 1 will be true, but if errorlevel 0 will also be true

setlocal
set /A sample =1 

:first
type C:\test.txt | find "inserted"

if errorlevel 1 goto exam
if errorlevel 0 goto test

:test
echo "testloop" >> C:\testloop.txt
set /A sample = %sample% + 1 

if %sample% LEQ 4 goto first

:exam
echo "exam loop" >> C:\examloop.txt

endlocal

if you have command extensions enabled, and there is no environment variable called ERRORLEVEL (case insensitive). Then in theory you can use %ERRORLEVEL% like an ordinary environment variable. So this should also work

setlocal EnableExtensions
set /A sample =1 

:first
type C:\test.txt | find "inserted"

if %errorlevel% EQU 1 goto exam
if %errorlevel% EQU 0 goto test

:test
echo "testloop" >> C:\testloop.txt
set /A sample = %sample% + 1 

if %sample% LEQ 4 goto first

:exam
echo "exam loop" >> C:\examloop.txt
John Knoeller