Windows 批处理变量不会设置 [英] Windows Batch Variables Won't Set
问题描述
我想我在 Window 的批处理脚本中遇到了一个错误.
I think I ran into a bug in Window's batch scripting.
我无法设置扩展 if 语句中的变量.
I cannot set variables that are in an expanded if statement.
这是我的脚本的一个孤立部分:
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.
)
这是一个全新的 cmd 实例的输出:
This is the output from a brand new instance of cmd:
C:UsersRandomClownDesktop>test.bat
Version: 12345
Type: 456
Target: Client
dir:
zip:
test: 42
test2:
您应该注意的是单行 if 语句正确设置了内容.多行 if 将执行任何非集合的操作.我不认为我错过了什么.此外,多行 if 语句正确执行了正确的行,因为 else ( echo Not success. )
行没有执行.
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.
为什么这些行没有执行?
Why did the lines not execute?
推荐答案
你错过了一些东西 ;-)
You missed something ;-)
cmd
在命令被解析时扩展变量,而不是在它们运行时.碰巧带有块 ( ... )
(或实际上任何块)的 if
或 for
语句在那种情况.因此,当您在块中设置变量并尝试在同一个块中使用它们时,不再有变量 - 它们被替换为变量在块执行之前之前的值.
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) counts as a single command in that case. So when you set variables inside a block and try using them in the same block there are no variables anymore – they were replaced by the values the variables had before the block even executed.
贴一个
setlocal enabledelayedexpansion
在批处理文件的开头并使用 !zip!
而不是 %zip%
.有关问题的详细讨论,请参阅 help set
.
at the start of your batch file and use !zip!
instead of %zip%
. See help set
for a detailed discussion of the problem.
这篇关于Windows 批处理变量不会设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!