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

  1. 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 that MYVAR is localized within the SETLOCAL/ENDLOCAL block.

  2. 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 by Original, showing how changes are reverted after ENDLOCAL.

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 the ENDLOCAL command.
  • Nesting: ENDLOCAL must be balanced with a preceding SETLOCAL. 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.

  • SETLOCAL: Begins localization of environment changes. Each SETLOCAL should have a corresponding ENDLOCAL.
  • SET: Creates or modifies environment variables within the localized environment.
  • CALL: Uses to call other batch files or subroutines, often used together with SETLOCAL and ENDLOCAL.

For further reading and more details on batch scripting, see Microsoft’s official documentation.