Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 297
sergej Avatar asked Dec 24 '22 06:12

sergej


2 Answers

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.

like image 196
Compo Avatar answered Jan 12 '23 09:01

Compo


Consider two batch files, a.bat and b.bat. The batch file a.bat calls b.bat and also calls a local subroutine :c.

   @echo off
   rem -------------
   rem This is a.bat
   rem -------------
   echo Outer A=%A%
   setlocal
   set A=Value_A
   echo Local A=%A%
   echo Calling b.bat
   call b.bat
   echo Back from b.bat
   echo A=%A%
   echo Calling subroutine :c
   call :c
   echo Back from subroutine :c
   echo A=%A%
   exit /b
:c
   setlocal
   set A=Value_C
   echo Inside subroutine :c A=%A%
   exit /b

 

   @echo off
   rem -------------
   rem This is b.bat
   rem -------------
   setlocal
   set A=Value_B
   echo Inside b.bat A=%A%

Running a.bat produces:

C> a.bat
Outer A=
Local A=Value_A
Calling b.bat
Inside b.bat A=Value_B
Back from b.bat
A=Value_A
Calling subroutine :c
Inside subroutine :c A=Value_C
Back from subroutine :c
A=Value_A

Note that there is no endlocal in sight.

like image 27
AlexP Avatar answered Jan 12 '23 10:01

AlexP