10

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

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Bharath
  • 665
  • 5
  • 12
  • 20

5 Answers5

7

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
  • 33,512
  • 4
  • 61
  • 92
3

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

See this explanation and example.

JRL
  • 76,767
  • 18
  • 98
  • 146
0

You may want to consider using ERRORLEVEL as direct branching as follows:

setlocal

set /A sample =1 

:first

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

**goto :Branch%ERRORLEVEL%**

:Branch0

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

set /A sample = %sample% + 1 

if %sample% LEQ 4 goto first

:Branch1

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

endlocal
Aleš
  • 8,896
  • 8
  • 62
  • 107
CarFan
  • 1
  • 1
0

May be use || instead of errorlevel for branching.

setlocal
set /a sample=1

:first
(Type c:\test.txt | find "inserted" >> c:\testloop.txt) || goto :branch1
set /a sample+=1
If %sample% leq 4 goto :first

:brabch1
Echo "exam loop" >> c:\examloop.txt
Stephan
  • 53,940
  • 10
  • 58
  • 91
0

More simple way to use for loop.

For /l %%a in (1,1,4) do (

(Type c:\test.txt | find “inserted” >> c:\testloop.txt) || goto :done

)

:done

Echo “exam loop” >> c:\examloop.txt

Goto :eof