Windows 批处理变量不会设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9681863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Windows Batch Variables Won't Set
提问by RandomClown
I think I ran into a bug in Window's batch scripting.
我想我在 Window 的批处理脚本中遇到了一个错误。
I cannot set variables that are in an expanded if statement.
我无法设置扩展 if 语句中的变量。
Here is an isolated part of my script:
这是我的脚本的一个孤立部分:
@echo off
set success=1
set Version=12345
set Target=Client
set Type=456
set dir=
set zip=
if "%Version%"=="" set success=0
if "%Type%"=="" set success=0
if 1==1 set test=42
if %success%==1 (
set test2=57005
if "%Target%"=="Client" (
set dir=ModName v%Version%
set zip=ModName v%Version% %Type%.zip
echo Version: %Version%
echo Type: %Type%
echo.
echo Target: %Target%
echo dir: %dir%
echo zip: %zip%
echo.
echo test: %test%
echo test2: %test2%
)
) else (
echo Not successful.
)
This is the output from a brand new instance of cmd:
这是一个全新的 cmd 实例的输出:
C:\Users\RandomClown\Desktop>test.bat
Version: 12345
Type: 456
Target: Client
dir:
zip:
test: 42
test2:
What you should notice is that the single line if statement correctly sets stuff.
The multiline if will perform anything that is NOT a set. I dont think I missed anything.
Also, the multiline if statement is correctly executing the right lines, as the else ( echo Not successful. )
lines did not execute.
您应该注意的是单行 if 语句正确设置了内容。多行 if 将执行任何非集合的操作。我不认为我错过了什么。此外,多行 if 语句正确执行正确的行,因为这些else ( echo Not successful. )
行没有执行。
Why did the lines not execute?
为什么这些行没有执行?
回答by Joey
You missed something ;-)
你错过了一些东西;-)
cmd
expands variables when commands are parsed, not when they are run. It so happens that an if
or for
statement with a block ( ... )
(or actually any block) counds as a single command in that case. So when you set variables inside a block andtry using them in the same block there are no variables anymore – they were replaced by the values the variables had beforethe block even executed.
cmd
在解析命令时扩展变量,而不是在运行时扩展变量。在这种情况下,带有块(或实际上任何块)的if
orfor
语句恰好是一个( ... )
命令。因此,当您在块内设置变量并尝试在同一块中使用它们时,变量就不再存在了——它们被替换为在块执行之前变量具有的值。
Stick a
贴一个
setlocal enabledelayedexpansion
at the start of your batch file and use !zip!
instead of %zip%
. See help set
for a detailed discussion of the problem.
在您的批处理文件和使用的开始!zip!
,而不是%zip%
。有关help set
该问题的详细讨论,请参见。
回答by Hyman Wu
Just a remind, the ms-dos "set" command takes every string after the equal sign. So if you write
提醒一下,ms-dos“set”命令在等号之后获取每个字符串。所以如果你写
if "x"=="x" set a=foo else set a=bar
echo %a% // output : foo else set a=bar
The %a% is actually set to "foo else set a=bar", not foo. So I always use "()" for set command if there are multiple commands in one line.
%a% 实际上设置为“foo else set a=bar”,而不是 foo。所以如果一行中有多个命令,我总是使用“()”作为设置命令。
if "%1"=="" (set a=20) else (set a=%1)