Skip to content

Instantly share code, notes, and snippets.

@Sedose
Last active July 22, 2025 12:17
Show Gist options
  • Select an option

  • Save Sedose/a2e452c0e69708e6fa742b02ff7fd203 to your computer and use it in GitHub Desktop.

Select an option

Save Sedose/a2e452c0e69708e6fa742b02ff7fd203 to your computer and use it in GitHub Desktop.
`setlocal` and `endlocal` commands

Understanding setlocal and endlocal in Batch Scripts

In a Windows batch script (.bat or .cmd), the commands setlocal and endlocal are used to create a local scope for environment variable changes.


setlocal

This marks the beginning of a local scope.
After this point, any environment variable changes (with set, call set, etc.)
are only visible within the current script or block and will be reverted after endlocal is reached.

Think of it like opening a temporary environment context.


endlocal

This ends the local scope started by setlocal,
discarding all changes made to environment variables inside that scope and restoring their previous values.


Example

@echo off
set MY_VAR=global
echo Before setlocal: %MY_VAR%

setlocal
set MY_VAR=local
echo Inside setlocal: %MY_VAR%
endlocal

echo After endlocal: %MY_VAR%

This outputs:

Before setlocal: global
Inside setlocal: local
After endlocal: global
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment