How to use goto in batch script

I wrote the 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 he will pass the "exam", although the error rate is not equal to "1". Plz help me

+6
batch-file
source share
5 answers

Your problem is not that this level of error requires special treatment, it is not like a normal environment variable. The only test you can do with the error level is to check if it is greater than or equal to the value.

so you need to check the error level values ​​from the highest to the lowest, because if the error level is 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 activated and there is no environment variable called ERRORLEVEL (case insensitive). Then, in theory, you can use% ERRORLEVEL% as a normal 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 
+6
source share

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

See this explanation and example .

+2
source share

You might want to use ERRORLEVEL as a direct branch 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 
0
source share

May be used || instead of the error level 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 
0
source share

A simpler way to use for a loop.

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

(Type c: \ test.txt | find "inserted" β†’ c: \ testloop.txt) || goto: done

)

: done

Echo "exam cycle" β†’ c: \ examloop.txt

Go to: eof

0
source share

All Articles