Local variables not cleaned-up on batch script crash

Microsoft Windows
Post Reply
User avatar
jesus2099
Posts: 2
Joined: 2023-Jul-25, 11:32 am

Local variables not cleaned-up on batch script crash

Post by jesus2099 »

I have a script that crashes on some syntax (French Windows 10):

Code: Select all

do était inattendu.
Which can be translated to:

Code: Select all

do was unexpected.
In this script I use setlocal.

Thanks to this crash, I noticed that exceptionally the local variables were not cleaned-up when there is a script crash!

I didn't find anything about this.
Do you know if there is a way to catch all errors and force endlocal?
jeb
Posts: 12
Joined: 2023-May-10, 1:28 pm

Re: Local variables not cleaned-up on batch script crash

Post by jeb »

Hi Jesus2099,

the problem/feature of the missing endlocal on syntax errors is known, see Exit from nested batch file.

It can be useful to examine all variables when a batch file crashes.

But in your case, you want a clean environment after calling a batch file, even after a syntax error.
I suppose, the only solution is to use a child process for this.

Code: Select all

@echo off
REM *** Trampoline jump
FOR /F "tokens=3 delims=:" %%L in ("%0") do goto :%%L

set test=original
REM *** Restart this batch file in a child process
cmd /c "%~d0\:Start:\..\%~pnx0"
echo Show the content of test after a crash
set "test"
exit /b

:start
setlocal 
set TEST=Content

REM *** Force a syntax error
()
Post Reply