Search notes:

cmd.exe: the setlocal command

setlocal localizes changes that are made to variables (in the documentation referred to as environment). The changes are reverted back with endlocal.
setlocal is affected by whether command extensions are enabled or disabled.
setlocal has no effect when not used in a batch file.

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%
Github repository about-cmd.exe, path: /commands/setlocal/variable.bat
This batch file prints
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
Github repository about-cmd.exe, path: /commands/setlocal/batch-file.bat
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

setlocalendlocal 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%
Github repository about-cmd.exe, path: /commands/setlocal/nesting.bat
This batch file prints:
VAR: ABC
VAR: DEF
VAR: GHI
VAR: DEF
VAR: ABC
VAR:

setlocal enableExtensions

Changes to command extensions in a batch file.

setlocal enableDelayedExpansion

Changes to delayed variable expansion in a batch file.

See also

Other cmd.exe commands

Index