setlocal
localizes changes that are made to
variables (in the documentation referred to as
environment). The changes are reverted back with
endlocal
.
Changes to environment variables
The following example
sets a
variable, then uses
setlocal
to go into a localized environment where it changes the value of the variabe, and then leaves the localized environment with
endlocal
and
prints the value of the variable again.
set VAR=hello
@echo VAR: %VAR%
@setlocal
@echo VAR: %VAR%
@set VAR=in localized environment
@echo VAR: %VAR%
@endlocal
@echo VAR: %VAR%
VAR: hello
VAR: hello
VAR: in localized environment
VAR: hello
Effect when calling a batch file
If a value is assigned to variable in a batch file, the variable will also have the assigned value in the calling environment unless the modification is protected with setlocal
.
This is demonstrated with the following simple batch file:
@echo off
set VAR_ONE=changed
setlocal
set VAR_TWO=will be reverted
C:\> set VAR_ONE=hello
C:\> set VAR_TWO=world
C:\> batch-file.bat
C:\> echo %VAR_ONE%
changed
C:\> echo %VAR_TWO%
world
Nesting setlocal/endlocal blocks
setlocal
… endlocal
blocks can be nested:
@echo off
setlocal
set VAR=ABC
setlocal
echo VAR: %VAR%
set VAR=DEF
echo VAR: %VAR%
setlocal
set VAR=GHI
echo VAR: %VAR%
endlocal
echo VAR: %VAR%
endlocal
echo VAR: %VAR%
endlocal
echo VAR: %VAR%
This batch file prints:
VAR: ABC
VAR: DEF
VAR: GHI
VAR: DEF
VAR: ABC
VAR: