我有一个批处理函数,我需要从中返回一个值。脚本如下:
@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%
不打印任何内容。任何帮助吗?我已经硬编码了set mode=OPEN
用于测试。
每个exit
,exit /b
或goto :eof
隐式地执行endlocal
,因此您需要一个技巧来让变量%1
在endlocal
中存活。endlocal & set ... & goto :eof
做到了这一点,因为整行代码一次被解析:
@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
)
出于同样的原因,子程序中的echo %mode1%
不打印变量。
注意:我把set
和if
的语法改成了推荐的引号语法。