Dan Stevens
Dan Stevens

Reputation: 6830

ECHO strange behavior when inside IF block

I have a Windows Batch script named test.bat as follows:

@ECHO OFF
SETLOCAL
SET name=Dan
SET greeting=Hi %name%, how are you?
ECHO %greeting%

When executed I get the following output:

Hi Dan, how are you?

This is what I would expected. I changed the script to the following:

@ECHO OFF
SETLOCAL
IF EXIST test.bat (
    SET name=Dan
    SET greeting=Hi %name%, how are you
    ECHO %greeting%
) ELSE (
    ECHO Nofile
)

I would expect to get the same output. Instead I get the following:

ECHO is off.

Please can someone help me understand why.

Upvotes: 1

Views: 641

Answers (1)

npocmaka
npocmaka

Reputation: 57252

you need delayed expansion:

@ECHO OFF
SETLOCAL enableDelayedExpansion
IF EXIST test.bat (
    SET name=Dan
    SET greeting=Hi !name!, how are you
    ECHO !greeting!
) ELSE (
    ECHO Nofile
)

The batch files have two phases of reading the script - execution and parsing. During parsing phase all variables enclosed with % are substituted and during execution phase the commands are executed. With the delayed expansion turned on the variables enclosed with ! will be expanded during execution phase (i.e. later)

Brackets on the other side (as well as &) puts the commands in a block taken as one single command so all variables with % are substituted during the first phase and when you are setting variables you'll need delayed expansion.

Upvotes: 4

Related Questions