ENDLOCAL - CMD
Overview
The ENDLOCAL
command in Windows Command Prompt is used to end the localization of environment changes in a batch file. When a batch file executes, environment variables and other settings can be modified locally within the scope of that script using SETLOCAL
. ENDLOCAL
ends that scope, restoring the environment to its previous state. This command is crucial for managing and containing environment changes without affecting the global system environment.
Syntax
The syntax for ENDLOCAL
is straightforward as it does not take any parameters:
ENDLOCAL
Options/Flags
ENDLOCAL
does not have any options or flags. Its sole purpose is to end the environment localization initiated by SETLOCAL
.
Examples
-
Simple Usage in a Batch File
@ECHO OFF SETLOCAL SET MYVAR=123 ECHO %MYVAR% ENDLOCAL ECHO %MYVAR%
The output will show
123
followed by%MYVAR%
, demonstrating thatMYVAR
is localized within theSETLOCAL/ENDLOCAL
block. -
Combining Multiple Commands
@ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION SET VAR=Original SET VAR=Modified inside SETLOCAL ECHO !VAR! ENDLOCAL ECHO %VAR%
This script will output
Modified inside SETLOCAL
followed byOriginal
, showing how changes are reverted afterENDLOCAL
.
Common Issues
- Invisible Changes: Sometimes changes made inside the localized environment are not evident outside the batch file or after the
ENDLOCAL
. Ensure that all tests and accesses to modified variables occur before theENDLOCAL
command. - Nesting:
ENDLOCAL
must be balanced with a precedingSETLOCAL
. Unmatched commands will either have no effect or could potentially lead to confusion regarding environment state.
Integration
Combining ENDLOCAL
with other CMD commands enhances script robustness and predictability:
@ECHO OFF
SETLOCAL
CALL :subroutine
ENDLOCAL
GOTO :EOF
:subroutine
SET RESULT=calculated value
ECHO Result is %RESULT%
GOTO :EOF
This script contains changes to the environment variables within a subroutine and ensures that the main environment remains unaffected.
Related Commands
SETLOCAL
: Begins localization of environment changes. EachSETLOCAL
should have a correspondingENDLOCAL
.SET
: Creates or modifies environment variables within the localized environment.CALL
: Uses to call other batch files or subroutines, often used together withSETLOCAL
andENDLOCAL
.
For further reading and more details on batch scripting, see Microsoft’s official documentation.