Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch delayed expansion not working

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:\>
like image 424
Richard Avatar asked Nov 28 '22 11:11

Richard


2 Answers

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

like image 36
user3200692 Avatar answered Dec 05 '22 06:12

user3200692


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
)
like image 171
atzz Avatar answered Dec 05 '22 05:12

atzz