我有一个批处理脚本,它应该可以访问一个名为 env:dev
的变量,所以它里面有一个冒号......这个变量是由第三方组件设置的,所以我对那个命名没有影响......
如何在我的批处理脚本中访问这个变量的内容?我知道 :
是一个特殊字符,所以我可以逃避它吗?以下不起作用:
echo %env:dev%
echo "%env:dev%"
echo %env^:dev%
...
有什么建议吗?
最佳答案
:
冒号在 CMD
环境变量中有特殊含义,例如,如果命令扩展被启用(Windows cmd
默认值)
- Variable Edit/Replace :
%variable:StrToFind=NewStr%
- Variables: extract part of a variable (substring) :
%variable:~num_chars_to_skip%
%variable:~num_chars_to_skip,num_chars_to_keep%
很难escape :
变量名中的冒号,如果可能的话根本不。这是一个解决方法:创建变量,其名称将 :
冒号替换为另一个字符,例如_
低线(下划线):
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
rem create sample variables
set "env:dev1=some thing!" value contains exclamation mark
set "env:dev2=some thing%%" value contains percent sign
set "an:other=some:thing3" another name containing colon
echo --- before ---
set env
set an
for /F "tokens=1* delims==" %%G in ('set') do (
set "auxName=%%G"
set "auxValue=%%H"
call :colons
)
echo --- after ---
set env
set an
rem
ENDLOCAL
goto :eof
:colons
if not "%auxName::=_%" == "%auxName%" set "%auxName::=_%=%auxValue%"
goto :eof
输出:
==> d:\bat\so\37973141.bat
--- before ---
env:dev1=some thing!
env:dev2=some thing%
an:other=some:thing3
--- after ---
env:dev1=some thing!
env:dev2=some thing%
env_dev1=some thing!
env_dev2=some thing%
an:other=some:thing3
an_other=some:thing3
==>
编辑:为了完整起见:
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
rem create sample variables
set "env:dev1=some thing!" value contains exclamation mark
set "env:dev2=some thing%%" value contains percent sign
set "an:other=some:thing3" another name containing colon
rem use sample variables
SETLOCAL DisableExtensions
echo Disabled Extensions %env:dev1% / %env:dev2% / %an:other%
ENDLOCAL
注意禁用命令扩展的影响,阅读cmd/?
:
The command extensions involve changes and/or additions to the following commands:
DEL or ERASE COLOR CD or CHDIR MD or MKDIR PROMPT PUSHD POPD SET SETLOCAL ENDLOCAL IF FOR CALL SHIFT GOTO START (also includes changes to external command invocation) ASSOC FTYPE
To get specific details, type commandname /? to view the specifics.
关于windows - 批处理变量名中的冒号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37973141/