How to use an environment variable as the name of an environment variable

In my quest to solve another problem related to the environment variable / batch file system, I again ran into a problem that I had visited before (but I can’t remember for life how, or even if I solved it).

Let's say you have two BAT files (or one batch file and a command line). How to pass the name of an environment variable to another so that it can read the variable? The following example does not work:

A.BAT: @call b.bat path B.BAT: @echo %%1% > A.BAT > %1 > B.BAT path > %1 

It's easy enough to pass the name of an environment variable, but the caller cannot use it. (I don’t remember when and how I dealt with this the last time it appeared, but I suspect that it required a less than ideal use of redirecting temporary BAT files and calling them, etc.)

Any ideas? Thanks.

+4
source share
2 answers

You can use a little trick, which, unfortunately, is not documented anywhere:

 call echo %%%1%% 

Then you can use the delayed extension:

 setlocal enabledelayedexpansion echo !%1! 

The delayed extension helps here mainly because it uses other delimiters for the variable and evaluates them immediately before running the command, while normally the evaluation may encounter a normal parameter extension.

Another way to convince this would be with a subroutine:

 call :meh "echo %%%1%%" ... :meh %~1 goto :eof 

All examples, including another answer, have one thing in common: they all force cmd to evaluate variables / parameters twice. This will not work otherwise, since the first estimate should produce %VariableName% , and the second will expand the contents of the variable.

You can also find my SVN code.

+4
source

B.BAT:

 FOR /F "delims=" %%a IN ('echo.%%%1%%') DO set inputvar=%%a echo %inputvar% 

This is one way to do this.

If all you want to do is echo you can do: echo.%%%1%%|more or echo %%%1%%|find /v ""

+2
source

Source: https://habr.com/ru/post/1306716/


All Articles