批处理脚本中如何使用goto

10
我写了下面的代码。
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",它也会标记为“exam”,请帮我解决。

5个回答

7
你的问题不是goto,而是errorlevel需要特殊处理,它不像普通环境变量那样。你只能测试errorlevel是否大于或等于某个值。因此,你必须从高到低测试errorlevel的值,因为如果errorlevel为1,则if errorlevel 1将为true,但if errorlevel 0也将为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

如果您启用了命令扩展,并且没有名为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

3

您需要按降序列出错误级别(errorlevel2,errorlevel1,errorlevel0...)。

请参见此说明和示例


0

您可能想考虑使用ERRORLEVEL作为直接分支,如下所示:

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

在分支语句中,可以使用||代替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

Stephan,感谢您的格式化,不知道为什么会出现代码格式不正确的问题。 - user9133538
因为您没有格式化任何内容。请参阅此处了解如何进行格式化。 - Stephan

0

使用for循环的更简单方法。

对于/l %%a in (1,1,4) do (

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

)

:完成

回声“考试循环” >> c:\examloop.txt

跳转 :eof


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接