批量分配变量 [英] Variable assignment in batch

查看:51
本文介绍了批量分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题似乎(非常)愚蠢,因为我无法处理它:(

This question seems to be (very) stupid be I can't deal with it :(

当我尝试此批处理代码时:

When I tried this batch code:

if "%1" == "-i" (
set is = %2
echo. %is%
shift
)

用两个(或更多)参数调用

,它不起作用.它实际上打印空白."shift"命令也不执行.当我观看执行的代码(开始时没有@echo时)时,可以看到"set"命令已完成.

called with 2 (or more) arguments, it does NOT work. It actually prints a blank. The "shift" command is not done either. When I watch the executed code (without the @echo off at the beginning), I can see that the "set" command is completed.

怎么了?

呼叫示例:

c:\script.bat -i test -d bla

推荐答案

您有两个问题.默认情况下,parens中的语句组将一次全部完成变量扩展,即在您的 set 命令之前.同样, set 的语义是错误的,您不希望 = 周围有空格.

You have two issues. By default group of statements in parens will have variable expansion done all at once, that is before your set command. Also the semantics for set is wrong, you don't want spaces around the =.

将此添加到文件顶部:

setlocal ENABLEDELAYEDEXPANSION

并删除 set 中的 = 周围的空格:

and remove the spaces around = in set:

set is=%2

最终使用的延迟扩展:

echo. !is!

第三个可能的问题是您可能需要两个 SHIFT ,一个用于 -i ,一个用于它的 is 参数.

A possible third issue is you may need two SHIFTs, one for -i, one for it's is argument.

感谢@dbenham指出这不是 set 的语法错误,这只是令人惊讶的行为,值得对此进行一些解释.如果执行以下命令:

Thanks to @dbenham for pointing out that it wasn't a syntax error with set, it's just surprising behavior that deserves a little explanation. If you execute these commands:

set a=one
echo "%a%"

结果是:

"one"

这很有道理,但请尝试:

That makes sense, but try:

set b = two
echo "%b%"

您会得到:

"%b%"

什么?这是未设置环境var b 时的期望.但是我们 just 进行设置.还是我们:

What? This is what you would expect when environment var b is unset. But we just set it. Or did we:

echo "%b %"

显示:

" two"

对于Windows set 命令,与我知道的任何其他语言或环境不同,空格非常重要. = 之前的空格将成为环境var名称的一部分,而之后的空格将成为值的一部分.这种不常见的行为是编写Windows批处理程序时常见的错误来源.

For the Windows set command, unlike any other language or environment I'm aware of, the spaces are significant. The spaces before the = become part of the environment var name, spaces after become part of the value. This uncommon behavior is a common source of errors when writing Windows batch programs.

这篇关于批量分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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