如何在批处理脚本中使用goto

Bha*_*ath 6 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 goto first

:exam

echo "exam loop" >> C:\examloop.txt

endlocal
Run Code Online (Sandbox Code Playgroud)

但即使错误级别不等于"1",它也将成为"考试",PLZ帮帮我

Joh*_*ler 6

你的问题不是goto,它的错误级别需要特殊处理,它不像普通的环境变量.您可以使用errorlevel进行的唯一测试是测试它是否大于或等于value.

所以你要测试从最高到最低ERRORLEVEL值,因为如果错误级别1,那么if errorlevel 1将是真实的,但if errorlevel 0为真

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
Run Code Online (Sandbox Code Playgroud)

如果启用了命令扩展,并且没有名为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
Run Code Online (Sandbox Code Playgroud)


JRL*_*JRL 3

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

请参阅此解释和示例