如何使用环境变量作为环境变量名称 [英] How to Use an Environment Variable as an Environment Variable Name

查看:279
本文介绍了如何使用环境变量作为环境变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的追求解决另一个环境变量/批处理文件相关的问题,我再次遇到我以前访问过的一个问题(但不能为我的生活记得,甚至的如果的我解决了它)。

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

假设你有两个BAT文件(或一个批处理文件和命令行)。一个人如何可以通过一个环境变量名的其他,以便它可以读取变量?下面的例子不工作:

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

这是很容易的通过环境变量名,但似乎被调用者不能使用它。 (我不记得是否或如何处理这个最后一次来了,但我怀疑它所需的低于理想的临时重定向BAT文件的,并呼吁他们,这样的使用。)

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

任何想法?谢谢你。

推荐答案

您可以使用一个小技巧不幸的是无处记载:

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

所有的例子,包括其他的答案,都有一个共同点这里:他们都力 CMD 评估变量/参数<​​EM>两次的这否则它不会工作,因为第一次评估必须出示%VARIABLENAME%,而第二个将展开为变量的内容。

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.

您可以找到code也我SVN

You can find the code also on my SVN.

这篇关于如何使用环境变量作为环境变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆