How to Use an Environment Variable as an Environment Variable Name

£可爱£侵袭症+ 提交于 2019-12-21 18:23:15

问题


In my pursuit of a solution to another environment-variable/batch-file related problem, I have once again come across a problem I have visited before (but cannot for the life of me remember how, or even if I solved it).

Say you have two BAT files (or one batch file and the command line). How can one pass an environment variable name to the other 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 is easy enough to pass the environment variable name, but the callee cannot seem to use it. (I don’t remember if or how I dealt with this the last time it came up, but I suspect it required the less-than-ideal use of redirecting temporary BAT files and calling them and such.)

Any ideas? Thanks.


回答1:


You can use a little trick which unfortunately is nowhere documented:

call echo %%%1%%

Then you can use delayed expansion:

setlocal enabledelayedexpansion
echo !%1!

Delayed expansion helps here mostly because it uses other delimiters for the variable and evaluates them directly prior to running the command, while normally the evaluation might clash with normal parameter expansion.

Another way of overdoing this would be a subroutine:

call :meh "echo %%%1%%"

...

:meh
%~1
goto :eof

All examples, including the other answer, have one thing in common here: They all force cmd to evaluate variables/parameters twice. It won't work otherwise, since the first evaluation must produce %VariableName%, while the second will expand that to the variable's contents.

You can find the code also on my SVN.




回答2:


B.BAT:

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

That is one way of doing it.

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



来源:https://stackoverflow.com/questions/2623704/how-to-use-an-environment-variable-as-an-environment-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!