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

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

问题描述

在我追求另一个环境变量/批处理文件相关问题的解决方案中,我再次遇到了我以前访问过的一个问题(但是不能让我的生活记住如何,甚至如果假设你有两个BAT文件(或一个批处理文件和命令行),那么你可以这样做。

如何将一个环境变量名称传递给另一个,以便它可以读取变量?以下示例不起作用:

  A.BAT:
@call b.bat路径

B.BAT:
@echo %% 1%

> A.BAT
> %1
> B.BAT路径
> %1

很容易传递环境变量名称,但被调用者似乎不能使用它。 (我不记得上次发生时是否或如何处理这个问题,但我怀疑它需要不太理想的方式重定向临时BAT文件并调用它们。)



任何想法?谢谢。

解决方案

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

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

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

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