批处理文件和函数返回值

批处理文件和函数返回值

我有一个包含多个例程的批处理文件。例子

:checkFileExists
if not exist %1\%2 (
echo %2 does not exist under %1
set returnValue=FAIL
exit /b 1 
) 
exit /b 0 
:checkPortNumber 
if %1 LSS 1024 (
port number should be greater than 1024 and less than 65535
set returnValue=FAIL
exit /b 1 
)
... other checks for port number
exit /b 0 
... main code.. 
set returnValue=OK
call :checkFileExists c:\tmp
echo %returnValue% 
call :checkFileExists c:\tmp2
echo %returnValue% 
call :checkPortNumber 89
echo %returnValue% 

c:\tmp 只是一个例子,它存在。我的返回值正确显示为 OK。c:\tmp2 不存在,我的 returnValue 正确显示为 FAIL。

我确实希望 checkPortNumber 测试失败,但 returnValue 始终设置为 OK。我也尝试过 setlocal enableDelayedExpansion,但没有成功。我是不是漏掉了什么?

答案1

重新排序/重新编写/重新格式化的代码的行为符合预期。

您的代码的主要问题是,您set returnValue=OK在开始时只执行一次子程序,即使set returnValue=Fail另一个子程序执行了该子程序,该子程序仍会继续存在exit /B 0

:: Q:\Test\2018\12\15\SU_1383774.cmd
@echo off
:: ... main code.. 

call :checkFileExists c:\tmp || Echo returned errorlevel %errorlevel%
echo %returnValue% 

call :checkFileExists c:\tmp2 || Echo returned errorlevel %errorlevel%
echo %returnValue% 

call :checkPortNumber 89 || Echo returned errorlevel %errorlevel%
echo %returnValue% 

Goto :Eof

:checkFileExists
if not exist "%~1\%~2" (
    echo %2 does not exist under %1
    set returnValue=FAIL
    exit /b 1 
) 
set returnValue=OK
exit /b 0 

:checkPortNumber 
if %1 LSS 1024 (
    echo port number should be greater than 1024 and less than 65535
    set returnValue=FAIL
    exit /b 1 
)
:: ... other checks for port number
set returnValue=OK
exit /b 0 

相关内容