退出前是否需要endlocal?

时间:2018-06-06 12:06:11

标签: windows batch-file cmd

我在批处理脚本中有以下“功能”:

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

请注意setlocal / endlocol对。

这里需要endlocal吗?还是多余的? exit是否隐含地结束了本地化?

加分问题: 可以在不测试行为的情况下回答这个问题,例如引用官方消息来源吗?

2 个答案:

答案 0 :(得分:3)

我不确定您是否想要提出某些问题但尚未确定,但鉴于您发布的脚本,您可以对其进行测试:

@Echo Off
Set "_variable="
Call :MyFunction "argument"
Set _variable
Pause
GoTo :EOF

:MyFunction
SetLocal
Set "_variable=%~1"
Exit /B 0

如果您收到一条说明Environment variable _variable not defined的消息,则SetLocal命令已关闭Exit,即Exit隐式结束了本地化。

答案 1 :(得分:2)

考虑两个批处理文件a.batb.bat。批处理文件a.bat调用b.bat并调用本地子例程: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%

运行a.bat会产生:

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

请注意,看不到endlocal