且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用环境变量作为环境变量名称

更新时间:2022-10-14 19:02:03

您可以使用一个不可思议的小技巧:

  call echo %%% 1 %% 

然后可以使用延迟扩展:

  setlocal enabledelayedexpansion 
echo!%1!

延迟扩展主要是因为它为变量使用其他分隔符,并在运行前直接评估它们命令,而通常评估可能与正常的参数扩展冲突。



另一种过度的方法将是一个子例程:

  call:mehecho %%% 1 %%

...

:meh
% 〜1
goto:eof

所有例子,包括其他答案,有一件事通常在这里:他们都强制 cmd 来评估变量/参数两次。否则将不起作用,因为第一次评估必须产生%VariableName%,而第二个将扩展到变量的内容。



您还可以在我的SVN


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.

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 *** 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.