how to use goto in batch script
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
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.
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
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
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
精彩评论