How to expand a CMD shell variable twice (recursively)

后端 未结 7 1023
温柔的废话
温柔的废话 2020-12-01 13:03

Using the Windows XP CMD command-line I can expand a variable twice as follows:

set AAA=BBB
set BBB=CCC
for /F \"usebackq tokens=*\" %i in (`echo %%AAA%%`) d         


        
7条回答
  •  被撕碎了的回忆
    2020-12-01 13:32

    The following (torturous) approach seems to work okay:

        @echo off
    :main
        setlocal enableextensions enabledelayedexpansion
        set aaa=bbb
        set bbb=ccc
        call :myset x %%aaa%%
        echo %x%
        endlocal
        goto :eof
    :myset
        for /F "usebackq tokens=*" %%i in (`echo %%%2%%`) do set %1=%%i
        goto :eof
    

    It outputs:

    ccc
    

    as desired.

    I've often used that trick to (for example) format %aaa% into %x% to a certain size (a la sprintf) but this is the first time I've had to do double indirection. It works because you don't find the extra "%%" being sucked up by the current shell level.

提交回复
热议问题