即使使用exit / b编号,调用批处理脚本也会以错误0退出

时间:2018-02-06 20:31:20

标签: 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有文字和除外

: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

Disclaimer.bat的返回错误0,即使退出是102

1 个答案:

答案 0 :(得分:1)

这相当于你的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

请注意,上面的代码不使用任何parens将代码行组合在一起,因此避免了延迟扩展的需要。脚本编写者花费更多时间来跟踪多行代码块中的问题,而不是代码中的任何其他代码块。即使延迟扩展,它也很难调试。最好采用更有条理的编码方式来避免多行代码块。

我测试了您的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时它返回零。