Home > Enterprise >  Return value from a cmd function
Return value from a cmd function

Time:06-19

I have a batch function and I need to return a value from it. Following is the script:

@echo off
call :Mode mode1
echo mode is %mode1%

:Mode
setlocal enabledelayedexpansion
set count=0
for /f "tokens=*" %%x in (map.txt) do (
    set /a count =1
    set var[!count!]=%%x
)

for /f "tokens=2 delims=: " %%A in ("%var[2]%") Do (
    set mode=OPEN
)
IF %mode%==OPEN (
    echo coming into open
    set %1=OPEN
    echo %mode1%
) ELSE (
    echo coming into shorted
    set %1=SHORTED
    echo %mode1%
) 
EXIT /B 0

echo mode is %mode1% doesn't print anything. Any help? I've hardcoded set mode=OPEN for testing purposes.

CodePudding user response:

Each exit, exit /b or goto :eof implicitly does an endlocal, so you need a trick for your variable %1 to survive an endlocal. endlocal & set ... & goto :eof does the trick because the whole line gets parsed in one go:

@echo off
call :Mode mode1
echo mode is %mode1%
goto :eof

:Mode
setlocal enabledelayedexpansion
set "mode=OPEN"
IF "%mode%" == "OPEN" (
    echo coming into open
    endlocal&set "%1=OPEN"&goto :eof
) ELSE (
    echo coming into shorted
    endlocal&set "%1=SHORTED"&goto :eof
) 

For the same reason, echo %mode1% in your subroutine does not print the variable.

Note: I changed set and if syntax to recommended quoted syntax.

  • Related