Alex
Alex

Reputation: 44325

Why does echo not print the text within an if statement (windows batch file)?

I have the following windows batch file:

 @echo off
 set MYVAR1=test
 set MYVAR2=
 set MYVAR3=a b c

 setlocal enableDelayedExpansion
 for /l %%x in (1, 1, 3) do (
    if !MYVAR%%x! == "" (
        echo Not defined
    ) else (
        echo Variable is: !MYVAR%%x!
    )
 )

I expect it to print the following output:

Variable is: test
Not defined
Variable is: a b c

instead I see the following output:

Variable is:  test
Variable is: 
Variable is: a b c

This does not make any sense to me! How can I change the batch script to get the desired output?

Upvotes: 0

Views: 86

Answers (2)

MC ND
MC ND

Reputation: 70923

An alternative to your now corrected code is not to test against the empty value but to use if defined

@echo off
    set "MYVAR1=test"
    set "MYVAR2="
    set "MYVAR3=a b c"

    setlocal enableDelayedExpansion
    for /l %%x in (1, 1, 3) do if not defined MYVAR%%x (
        echo Variable %%x Not defined
    ) else (
        echo Variable %%x is: !MYVAR%%x!
    )

Upvotes: 0

Alex
Alex

Reputation: 44325

One needs to enclose the delayed expression in quotation marks as well.

if "!MYVAR%%x!" == "" (

instead of

if !MYVAR%%x! == "" (

so the example code now looks like:

@echo off
set MYVAR1=test
set MYVAR2=
set MYVAR3=a b c

setlocal enableDelayedExpansion
for /l %%x in (1, 1, 3) do (
   if "!MYVAR%%x!" == "" (
    echo Not defined
    ) else (
        echo Variable is: !MYVAR%%x!
    )
 )

Upvotes: 1

Related Questions