6

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):

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:

@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:\>
Richard
  • 63
  • 1
  • 1
  • 4

4 Answers4

24

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

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
)
atzz
  • 17,507
  • 3
  • 35
  • 35
  • 1
    Nope, in that case the output is "if "!VAR!" == "after"". – Richard Nov 19 '09 at 12:31
  • 3
    Don't worry about the commands you're seeing echoed the screen; the point of delayed expansion is that it's done after that. Put an @ECHO OFF at the top of your script and you'll see that it's working. – David Webb Nov 19 '09 at 12:44
  • 1
    HoursWasted++; Thanks! That's twice that's got me. – Tim Abell Jul 26 '12 at 15:59
2

At the beginning of the cmd prompt, you must type “CMD /V” OR “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

  • 3
    `cmd /v` is superfluous, as `setlocal EnableDelayedExpansion` enable it, but `setlocal` only works in batch files. `cmd /v` is only necessary, if you want to use delayed expansion directly on the command line – jeb Nov 08 '18 at 07:22
1

dont use == , in batch you must use EQU

For Example write:

if %bla% EQU %blub% echo same
meh
  • 22,090
  • 8
  • 48
  • 58
rapster
  • 19
  • 1
  • 2
    This is nonsense, the only difference between `==` and `EQU` is the comparing of numbers. `IF 16 EQU 0x10` is true, but `IF 16 == 0x10` is false, as it compares always strings – jeb Nov 08 '18 at 07:19
0

I found your problem.

set VAR=after;

delete ; from the code above

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123