简体   繁体   中英

Colon in batch variable name

I have a batch script which should have access to a variable named something like env:dev , so it has a colon inside... this variable is set by a third-party component, so I don't have influence on that naming...

How can I access the content of this variable in my batch script? I know that : is a special character, so can I perhaps escape it? The following doesn't work:

echo %env:dev%
echo "%env:dev%"
echo %env^:dev%
...

Any suggestions?

A : colon has special meaning in CMD environment variables if command extensions are enabled (Windows cmd default), for instance

Hard to escape a : colon in variable name, if possible at all . Here's a workaround: create variables with such names that : colon is replaced by another character, eg _ Low Line (underscore):

@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

Output :

==> 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

==>

Edit : for the sake of completeness:

@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 

Be aware of disabling command extensions impact, read 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM