Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do batch files support exit traps?

Tags:

batch-file

Do Windows .bat scripts have an exit-trap like feature, that would allow registration of cleanup actions that always need to be run?

I am not interested in any solution that uses Powershell or other shells (I already have Python installed on the target system so if that can't be done in batch files I'll just wrap a bunch of calls to subprocess.Popen in try...finally).

like image 685
antony Avatar asked Mar 05 '15 22:03

antony


2 Answers

No, there are no exceptions, and no formal way of registering an exit routine to run automatically upon termination.

However, you can get close if you do not need environment changes to persist after the script terminates. You can run the majority of your script in a new CMD session, and then you can have cleanup routines in the parent level that will always run upon termination as long as the console window is not killed. Control will be returned back to the outer shell if the inner script terminates normally, or terminates due to Ctrl-C, or terminates due to fatal syntax error, etc.

Here is a trivial demonstration:

@echo off
if "%~1" equ ":main" (
  shift /1
  goto main
)
cmd /d /c "%~f0" :main %*
echo Cleanup actions go here
exit /b

:main
echo Main actions go here
exit /b

UPDATE - Hacked exceptions

I have since developed an effective exception hack using nothing but native batch commands - See Does Windows batch support exception handling?.

Exceptions can be thrown at any level of your code, and the exception bubbles up until a catch block handles the exception. The code cannot recognize errors on its own - each exception must be explicitly thrown by your code. It also cannot respond to , fatal syntax errors, or closed console. But if those limitations are acceptable, then it is an extremely effective way of installing cleanup code.

like image 92
dbenham Avatar answered Oct 02 '22 16:10

dbenham


Batch doesn't support anything like this.

However, cmd also doesn't have exceptions and very few ways of abnormally terminating a script (a syntax error in your script, or crashing cmd.exe for example). If your script doesn't intentionally terminate itself, it should be safe to simply put any cleanup at the end of your script.

To go further, you can call your batch file in a subshell from another batch file, and have the outer script do your cleanup. Then, no matter what happens in the script, the outer shell will just run the next command in the outer batch when it finishes.

like image 21
Ryan Bemrose Avatar answered Oct 02 '22 18:10

Ryan Bemrose