'Set variable inside if statement not working [duplicate]

I have file1.txt and test.bat in the same folder.

Inside test.bat:

This works:

SET test=file1.txt
COPY %test% file2.txt

This does not work:

IF ""=="" (
SET test=file1.txt
COPY %test% file2.txt
)

Why? The only difference is "if" statement.

Whats more interesting:

IF ""=="" (
COPY file1.txt file2.txt
)

works



Solution 1:[1]

This works:

setlocal enabledelayedexpansion 

IF ""=="" (
SET test=file1.txt
COPY !test! file2.txt
)

More about "enabledelayedexpansion": https://ss64.com/nt/delayedexpansion.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Przemek