批处理函数中无需额外传值,如何获取按引用传递的变量值?
问题
在以下批处理脚本中,var1按引用传递给myDosFunc函数,函数可以修改它的值。现在需要在函数内获取该引用变量的值,不需要同时传递变量及其值:
set "var1=Hello world" Echo var1 before: %var1% call :myDosFunc var1 "%var1%" Echo var1 after : %var1% goto :eof :myDosFunc -- passing a variable by reference, and changing value echo Notice that a variable passed by reference does NOT echo the value, and it echos the variable name instead. echo Arg1 variable name = '%~1' and Arg2 value = '%~2' set "%~1=Good bye world!!!" goto :eof
我尝试了多种写法,但都无法获取变量的值:
set "var1=Hello world" Echo var1 before: %var1% call :myDosFunc var1 Echo var1 after : %var1% goto :eof :myDosFunc -- passing a variable by reference, and changing value set "VarValue=%~1" set "VarVal=%~1%" echo Arg1 variable name = '%~1' and to get value, tried this '%%%VarValue%%%' and this '%%VarValue%%' and this '%VarValue%' and this '%%%VarVal%%%' and this '%%VarVal%%' and this '%VarVal%' set "%~1=Good bye world!" goto :eof
解决方法
在批处理中通过变量名(引用)获取对应的值,有两种可靠的实现方式:
方法1:启用延迟扩展
通过setlocal enabledelayedexpansion开启延迟扩展后,就能用!变量名!的语法动态解析变量值。修改后的脚本如下:
set "var1=Hello world" Echo var1 before: %var1% call :myDosFunc var1 Echo var1 after : %var1% goto :eof :myDosFunc setlocal enabledelayedexpansion rem 获取引用变量的值 set "VarValue=!%~1!" echo Arg1 variable name = '%~1' , value = '!VarValue!' endlocal & set "%~1=Good bye world!" rem 结束局部作用域时传递修改后的值到外部 goto :eof
注:
endlocal & set "%~1=..."的写法是为了避免setlocal的作用域隔离,确保修改后的变量值能传递到函数外部。
方法2:利用call命令的二次解析特性
借助call命令的二次解析能力,通过嵌套的百分号语法获取变量值:
set "var1=Hello world" Echo var1 before: %var1% call :myDosFunc var1 Echo var1 after : %var1% goto :eof :myDosFunc rem 通过call实现二次解析,获取引用变量的值 call set "VarValue=%%%~1%%" echo Arg1 variable name = '%~1' , value = '%VarValue%' set "%~1=Good bye world!" goto :eof
原理:%%%~1%%会先被解析为%var1%,随后call命令会再次解析这个字符串,最终得到var1的实际值。
内容的提问来源于stack exchange,提问作者David Maisonave
相关产品推荐
相关产品推荐

