Ankit Aggarwal
Ankit Aggarwal

Reputation: 23

Different behavior with delayed variable expansion in batch script in 2 identical piece of code

@echo off
pushd

setlocal enabledelayedexpansion enableextensions

set VARY=before
if "!VARY!" == "before" (
set VARY=2    
if "!VARY!" == "2" @echo If you see this, yes echo !VARY!
)


set VAR=before
if "!VAR!" == "before" (
set VAR=1
if "!VAR!" == "1" @echo If you see this, it worked
)

popd

Expected Output:
If you see this, yes 2
If you see this, it worked

Actual Output:
If you see this, it worked

Can someone explain why is the output not showing "If you see this, yes 2" as well?

Upvotes: 2

Views: 103

Answers (2)

jeb
jeb

Reputation: 82247

It's simple. The first time you set VARY to 2<space><space><space><space> instead of 2.

To avoid this use ALWAYS the syntax set "VARY=2"

This syntax only takes the input from the first to the last quote, all characters after the last quote are dropped.

Upvotes: 1

Endoro
Endoro

Reputation: 37569

You have trailing spaces after the 2, so compare if "2 " == "2" (not equal).

To avoid this use the following code:

set "VARY=before"
if "!VARY!" == "before" (
set  "VARY=2"
if "!VARY!"=="2" echo If you see this, yes echo !VARY!
)

.. and if you set numbers, you can also use "set /a":

set "VARY=before"
if "!VARY!" == "before" (
set /a VARY=2
if "!VARY!"=="2" echo If you see this, yes echo !VARY!
)

Upvotes: 2

Related Questions