Colon in batch variable name

后端 未结 1 1951
不知归路
不知归路 2021-01-03 12:36

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 com

1条回答
  •  抹茶落季
    2021-01-03 13:07

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

    • 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%

    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, e.g. _ 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.

    0 讨论(0)
提交回复
热议问题