windows 批量延迟扩展不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1762851/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:27:53  来源:igfitidea点击:

Batch delayed expansion not working

windowsbatch-filedelayedvariableexpansion

提问by Richard

Ok, I'm getting crazy and I don't know what else to do, I've tried several things and nothing is working.

好吧,我快疯了,我不知道还能做什么,我已经尝试了几件事,但没有任何效果。

Look at this sample code (test.cmd):

看看这个示例代码(test.cmd):

setlocal enabledelayedexpansion enableextensions
set VAR=before
if "%VAR%" == "before" (
    set VAR=after;
    if "%VAR%" == "after" @echo If you see this, it worked
)

This is the generated output:

这是生成的输出:

D:\>ver

Microsoft Windows [Version 6.1.7600]

D:\>test.cmd

D:\>setlocal enabledelayedexpansion enableextensions

D:\>set VAR=before

D:\>if "before" == "before" (
set VAR=after;
 if "before" == "after"
)

D:\>

Am I doing something wrong?

难道我做错了什么?

This is just a test, the code I need uses variables too and needs delayed expansion, but it this simple test doesn't work the other wont work either (I've tried, I ended up with a simple example to test if it worked).

这只是一个测试,我需要的代码也使用变量并且需要延迟扩展,但是这个简单的测试不起作用,另一个也不起作用(我已经尝试过,我最终得到了一个简单的例子来测试它是否有效)。

EDIT: New code and output:

编辑:新代码和输出:

test.cmd:

测试.cmd:

@echo off
setlocal enabledelayedexpansion enableextensions
set VAR=before
if "%VAR%" == "before" (
   set VAR=after;
   if "!VAR!" == "after" (
      echo It worked.
   ) else (
      echo It didn't work.
   )
)

Output:

输出:

D:\>test.cmd
It didn't work.

D:\>

回答by atzz

You have to use !var!for delayed expansion. %var%is always expanded on parse stage.

您必须使用!var!延迟扩展。%var%总是在解析阶段扩展。

I.e., change your code to

即,将您的代码更改为

setlocal enabledelayedexpansion enableextensions
set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "!VAR!" == "after" @echo If you see this, it worked
)

回答by user3200692

At the beginning of the cmd prompt, you must type “CMD /V” OR “CMD /V:ON”

在cmd提示符的开头,你必须输入“CMD /V”或“CMD /V:ON”

After this testing code should work

在此测试代码应该工作之后

SETLOCAL EnableDelayedExpansion
Set "_var=first"
Set "_var=second" & Echo %_var% !_var!

You should be able to see output “first second” sample cmd prompt screen

您应该能够看到“第一秒”的输出 示例 cmd 提示屏幕

回答by rapster

dont use == , in batch you must use EQU

不要使用 == ,批量你必须使用 EQU

For Example write:

例如写:

if %bla% EQU %blub% echo same

回答by Jason Li

I found your problem.

我发现了你的问题。

set VAR=after;

delete ;from the code above

;从上面的代码中删除