Page 1 of 1

SETLOCAL continues after batch termination!

Posted: 08 Jun 2011 16:30
by dbenham
OK - I think this is kind of scary

It is possible for a SETLOCAL within a batch file to remain in effect even after the batch file terminates! If two SETLOCAL are in effect and a fatal error occurs (any fatal error?), only the last SETLOCAL is ended. The first one remains in effect even after batch termination :!: :shock: I wasted many hours trying to diagnose why I was getting screwy results. :roll: For a while I thought I was going crazy!

test.bat

Code: Select all

@echo off
setlocal DisableExtensions EnableDelayedExpansion
set test=AFTER 1st SETLOCAL
setlocal
set test=AFTER 2nd SETLOCAL
if =broken if

Interactive session:

Code: Select all

>set test=before 1st SETLOCAL

>set test
test=before 1st SETLOCAL

>echo !test!
!test!

>set /a 5+5
10
>test
if was unexpected at this time.

>set test
The syntax of the command is incorrect.

>echo !test!
AFTER 1st SETLOCAL

>set /a 5+5
The syntax of the command is incorrect.


Dave Benham

Re: SETLOCAL continues after batch termination!

Posted: 17 Jul 2011 11:12
by dbenham
I found another situation where SETLOCAL persists after script termination: Whenever a fatal syntax error occurs within a CALLed routine while command extensions are enabled :!:

test.bat

Code: Select all

@echo off
setlocal EnableDelayedExpansion
set test=AFTER SETLOCAL
call :SyntaxError
exit /b

:SyntaxError
for

Interactive session:

Code: Select all

>set test=BEFORE SETLOCAL

>echo %test%
BEFORE SETLOCAL

>echo !test!
!test!

>test
The syntax of the command is incorrect.

>echo !test!
AFTER SETLOCAL

>


Dave Benham

Re: SETLOCAL continues after batch termination!

Posted: 18 Jul 2011 12:22
by Acy Forsythe
What's even worse is you have to close out of the command session to get rid of them. I was unable to get an endlocal command to get rid of my variables...

Re: SETLOCAL continues after batch termination!

Posted: 12 Aug 2011 13:49
by jeb
Acy Forsythe wrote:What's even worse is you have to close out of the command session to get rid of them. I was unable to get an endlocal command to get rid of my variables...


Yes this is interesting, what happens internally?

And it seems to be the only way to change the delayed expansion mode (and the extension mode) for the current cmd instance!

jeb