windowsbatch-filecmd

Is endlocal required before exit?


I have the following "function" in a batch scripts:

:myfunction
    setlocal
    set _variable=%*
    :: do something with %_variable%
    endlocal
    exit /B 0

Note the setlocal / endlocol pair.

Is endlocal required here? Or is it redundant? Does exit end the localization implicitly?

Bonus question: Can this question be answered without testing the behavior, for example by citing an official source?


Solution

  • I'm not really sure whether there's something you're wanting to ask, yet haven't, but given your posted script you could have tested it thus:

    @Echo Off
    Set "_variable="
    Call :MyFunction "argument"
    Set _variable
    Pause
    GoTo :EOF
    
    :MyFunction
    SetLocal
    Set "_variable=%~1"
    Exit /B 0
    

    If you receive a message stating Environment variable _variable not defined then SetLocal was closed by the Exit command, i.e. Exit implicitly ended the localization.