- 1 year ago
In windows batch file, re-set variable inside if-else block doesn't work
In Windows batch files, variables set within an if
or else
block are scoped to the block itself. This means that any changes made to the variable inside the block will not persist outside of the block.
To overcome this limitation, you can enable delayed variable expansion using the setlocal enabledelayedexpansion
command at the beginning of your batch file. This allows you to use the !variable!
syntax to access variables inside blocks and have the changes persist outside of the block.
Here's an example to illustrate the usage of delayed variable expansion:
batch@echo off
setlocal enabledelayedexpansion
set myVariable=Original Value
echo Before if-else: %myVariable%
if 1==1 (
set myVariable=New Value
echo Inside if: %myVariable%
) else (
set myVariable=Another Value
echo Inside else: %myVariable%
)
echo After if-else: %myVariable%
In this example, the variable myVariable
is set to different values inside the if
and else
blocks. By enabling delayed variable expansion, the changes to myVariable
are reflected correctly outside of the blocks.
Note: When using delayed variable expansion, you need to use !
instead of %
to access the variable within the block. For example, !myVariable!
instead of %myVariable%
.