Batch file and returning values from functions
5,721
This reordered/reworked/reformatted code behaves as expected.
Main problem with your code is that you only set returnValue=OK
once at the beginning, if a subroutine set returnValue=Fail
this does persist even if another sub does 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
Related videos on Youtube
Author by
SESHAGIRI SRIRAM
Updated on September 18, 2022Comments
-
SESHAGIRI SRIRAM over 1 year
I have a batch file that has multiple routines. examples
: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 is just an example and it exists. my return value correctly displays as OK. c:\tmp2 does not exist and my returnValue correctly displays as FAIL.
I do expect checkPortNumber to fail the test but returnValue is set to OK always. I have tried with setlocal enableDelayedExpansion also and not. Is there something I am missing?
-
DavidPostill over 5 yearsIt would be a better answer if you explained why this works when the original code doesn't.