Batch file 调用批处理脚本退出,错误为0,即使退出编号为/b

Batch file 调用批处理脚本退出,错误为0,即使退出编号为/b,batch-file,Batch File,我有一个批处理脚本start.bat @echo off SET Cp=0 if "%Cp%" EQU "0" ( CALL "Disclaimer.bat" if %ERRORLEVEL% EQU 102 ( contiue code here ) else ( goto :eof ) ) Disclaimer.bat包含文本和Exception or not :dsr SET /P dsrc=Do you accept the disclaimer (Y)es (N)o [Y/N]? if

我有一个批处理脚本start.bat

@echo off
SET Cp=0
if "%Cp%" EQU "0" (
CALL "Disclaimer.bat"
if %ERRORLEVEL% EQU 102 (
contiue code here
) else (
goto :eof
)
)
Disclaimer.bat包含文本和Exception or not

:dsr
SET /P dsrc=Do you accept the disclaimer (Y)es (N)o [Y/N]?
if /I "%dsrc%" EQU "Y" exit /B 102
if /I "%dsrc%" EQU "N" goto :eof
goto dsr

尽管exit为102,但Disclaimer.bat返回的是错误0。这相当于start.bat脚本,只是它在变量展开的相对计时方面没有任何问题:

@setlocal ENABLEEXTENSIONS
@rem @set prompt=$G

@if "%Cp%" neq "0" exit /b 0
@call "Disclaimer.bat"
@if %ERRORLEVEL% neq 102 @exit /b 0
contiue code here
注意,上面的代码不使用任何paren将代码行分组在一起,因此避免了延迟扩展的需要。脚本编写者花在跟踪多行代码块中的问题上的时间比他们代码中的任何其他地方都多。即使扩展延迟,也很难调试。您最好采用一种更有组织的编码方式,避免多行代码块

我测试了你的Disclaimer.bat脚本,得到了以下结果:

> test
Do you accept the disclaimer (Y)es (N)o [Y/N]?Y

>if /I "Y" EQU "Y" exit /B 102

14:44:47.74
D:\TMP\Joseph

> echo %errorlevel%
102

14:45:08.96
D:\TMP\Joseph

> test
Do you accept the disclaimer (Y)es (N)o [Y/N]?N

>if /I "N" EQU "Y" exit /B 102

>if /I "N" EQU "N" goto :eof

14:45:21.87
D:\TMP\Joseph

> echo %errorlevel%
0

显然,您关于Disclaimer.bat行为的假设是不正确的。当用户输入
Y
时,它返回102;当用户在提示下输入
N
时,它返回零。

键入
set/?
并阅读有关延迟扩展的信息。测试正常方式,它将工作-
如果错误级别182如果不是错误级别183命令
多行代码块经常出现问题。避开它们。您如何知道Disclaimer.bat返回零?为什么要检查
Cp
是否为零?您只需在if语句之前将其设置为零。好的,使用!Cp是以早期代码为条件的,这里给出Cp只是为了表明它是在早期代码工作时设置的。由于未使用,我重复了Disclaimer.bat的返回值为0!!我在start.bat中使用echo for error作为调用的返回路径,该调用给出0 Disclaimer.bat的应答是Y还是N我使用SETLOCAL EnableDelayedExpansion和!!而不是start.bat中调用Disclaimer.bat的%%。我以前曾尝试在start.bat中使用SETLOCAL EnableDelayedExpansion,但是我在错误的位置使用了它,因此它没有任何作用