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
Usage: GOTO can only be used in batch files. After a GOTO command in a batch file, the next line to be executed will be the one immediately following the label. The label must begin with a colon [:] and appear on a line by itself, and cannot be included in a command group.
In a nutshell, the goto command is a way to control the flow of a batch file. Typically, when you execute a batch file, the script executes from top to bottom following each line. But sometimes, you need the script to start executing at a different place in the script. The goto command is perfect for this.
GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function call normally returns control.
This line continuation character can help. A. The Windows command prompt (cmd.exe) allows the ^ (Shift + 6) character to be used to indicate line continuation. It can be used both from the normal command prompt (which will actually prompt the user for more input if used) and within a batch file.
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
You need to list the error levels in descending order (errorlevel2, errorlevel1, errorlevel0...).
See this explanation and example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With