Lolly
Lolly

Reputation: 36422

Batch script ENDLOCAL / SET inside if statement is not working

I am new to batch scripts and I am writing a batch script to set the environment variable. Below is the batch script I use for it.

if 1 == 1 (
    setlocal enableextensions enabledelayedexpansion
    SET name1=%1_hello
    endlocal & SET name=%name1%
    echo varaiable %name%
    goto :eof
)

But I am facing the issue the variable name is not getting set and name1 in endlocal & SET name=%name1% is always null or getting it from previously set environment variable. But the same code without if statement works.

    setlocal enableextensions enabledelayedexpansion
    SET name1=%1_hello
    endlocal & SET name=%name1%
    echo varaiable %name%
    goto :eof

In the above code the name1 variable is getting set and name is getting displayed. How can I get rid of this problem? Why endlocal / set behaves differently with if statement ?

Upvotes: 1

Views: 821

Answers (1)

Magoo
Magoo

Reputation: 80023

When the IF statement is parsed - and that's from the IF through to its closing parenthesis, ALL %var% are replaced by the contents of those variables as they stood at the time the line was PARSED, that is BEFORE execution.

Upvotes: 4

Related Questions