命令行返回值



我有一个批处理函数,我需要从中返回一个值。脚本如下:

@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 /bgoto :eof隐式地执行endlocal,因此您需要一个技巧来让变量%1endlocal中存活。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%不打印变量。

注意:我把setif的语法改成了推荐的引号语法。

相关内容

  • 没有找到相关文章

最新更新