Batch file 如何在批处理脚本中使用goto
我已经编写了以下代码Batch file 如何在批处理脚本中使用goto,batch-file,Batch File,我已经编写了以下代码 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 go
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
但是,即使错误级别不等于“1”,它也会标记为“检查”。请帮助我。您需要按降序列出错误级别(错误级别2、错误级别1、错误级别0…)
请参阅。您的问题不是goto,而是errorlevel需要特殊处理,它不像普通的环境变量。使用errorlevel可以执行的唯一测试是测试它是否大于或等于值 因此,您必须从最高到最低测试errorlevel值,因为如果errorlevel 1 然后
如果errorlevel 1
将为真,但是如果errorlevel 0
也将为真
如果您启用了命令扩展,并且没有名为ERRORLEVEL(不区分大小写)的环境变量。理论上,您可以像使用普通环境变量一样使用%ERRORLEVEL%。所以这也应该起作用
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
您可能想考虑使用<代码> ErrRealeS/<代码>作为直接分支如下:
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
可以使用
|
代替errorlevel进行分支
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
使用for循环的更简单方法 对于(1,1,4)do中的/l%%a( (键入c:\test.txt |查找“插入的”>>c:\testloop.txt)| |转到:完成 ) :完成 Echo“检查循环”>>c:\examloop.txt
Goto:eofStephan,多亏了格式正确,所以不要用正确的格式发布代码。因为你没有格式化任何东西。看看如何做。
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