如何把变量值里面一批又可变的名字吗? [英] How to put variable value inside another variable name in batch?

查看:101
本文介绍了如何把变量值里面一批又可变的名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Supose我有一个批处理脚本定义以下变量:

Supose I have defined the following variables in a batch script:

set VariableFirst=value1
set VariableLast=value2

和我在

set Type=First

和我想访问变量%VariableFirst%或%VariableFirst%取决于变量%类型%值(类似回声%变量类型%%% 但是这并未'T工作)。我怎样才能做到这一点在Windows批处理脚本?

and I wanna access variables %VariableFirst% or %VariableFirst% depending on the value of variable %Type% (Something like echo %Variable%Type%% but this doesn't work). How can I do that in a Windows batch script?

推荐答案

在您的具体情况下,这应该工作:

In your specific case this should work:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
set VariableFirst=value1
set VariableLast=value2
set Type=First
echo !Variable%Type%!

下面的解释是:

关键是 SETLOCAL EnableDelayedExpansion 。通常你的变量在分析时进行评估。考虑这个code:

The key is SETLOCAL EnableDelayedExpansion. Usually your variables are evaluated at parse time. Consider this code:

@ECHO OFF
SET a=b
SET b=abc
ECHO %%a%%

您想%A%来进行评估,以K所以 ECHO %%一个%% 会变成 ECHO%b%,输出会是ABC。但是这不会以这种方式工作。评估在分析时表示该变量的值不处理code设置。 设置A = B 集合B = ABC 将工作,但ECHO %%一个%%不会因为要知道%一%为b的第一行已被执行,但执行情况的 的变量设置后。所以%%一个%% bevomes%一%,输出只是%一%

You want %a% to be evaluated to K so ECHO %%a%% would turn ECHO %b% and the output would be abc. But this won't work this way. Evaluation at parse time means that the values of the variables are set without processing the code. SET a=b and SET b=abc will work but ECHO %%a%% wont because to know that %a% is b the first line has to be executed but the execution happens after the variables are set. So %%a%% bevomes %a% and the output is just %a%.

您需要做的是迫使国米preTER评估在最后一行的运行时间指行执行行,当你达到它评估的最后一行。要做到这一点,你需要添加 SETLOCAL EnableDelayedExpansion 在脚本的开始。现在!......!强制间preTER评估考虑这是该行前变量所做的所有更改的感叹号包围变量的当前值。

What you need to do is to force the interpreter to evaluate the last line at run time means execute line by line and evaluate the last line as you reach it. To do so you need to add SETLOCAL EnableDelayedExpansion at the beginning of your script. Now !...! forces the interpreter to evaluate the current value of the variable surrounded by the exclamation marks considering all changes which were made to variables before this line.

现在来看看这个:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET a=b
SET b=abc
ECHO !%a%!

现在一个是B,B是ABC和!%A%!在运行时进行评估。因此,在这种情况下 ECHO!%一%!在其中,在控制台知道一个点评价为%A%是b和可替换!%一%!有!b!这是ABC。所以输出为abc。

Now a is b, b is abc and !%a%! is evaluated at run time. So in this case ECHO !%a%! is evaluated at a point where the console knows that %a% is b and can replace !%a%! with !b! which is abc. So the output is abc.

这篇关于如何把变量值里面一批又可变的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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