loop
loop

Reputation: 3590

Batch file if statement weirdness with variable assignment and expansion

I have a batch file and I'm trying to work with some variables in an if statement. For example I set a variable either from command line parameter 1, or if there is no parameter 1 then I have a default value. Then, depending on whether the value is the default or an argument from the command line I perform some other function.

What I notice is that the variable I've assigned in the if statement isn't available after the if statement is over. Can someone explain why that is?

For example this will fail to echo what's in TEST1:

@echo off
setlocal ENABLEEXTENSIONS

if .%1==. (
    set TEST1=NOTFOUND
    echo %TEST1%
) else (
    set TEST1=%1
    echo %TEST1%
)

If I run that batch file with or without an argument it returns ECHO is off.. It thinks the variable is still empty.

If I attempt to get the variable after the if statement, it works:

@echo off
setlocal ENABLEEXTENSIONS

if .%1==. (
    set TEST1=NOTFOUND
) else (
    set TEST1=%1
)
echo %TEST1%


I'm sure this has to do with variable expansion but it really threw me. It looks like I will assign another variable in the if statement like set USING_DEFAULT_TEST1=TRUE and set USING_DEFAULT_TEST1=FALSE or compare to the default value or something.

Upvotes: 0

Views: 162

Answers (1)

Magoo
Magoo

Reputation: 79983

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed.

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

Upvotes: 1

Related Questions