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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With