Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a bat file know its name and can it delete itself

At some point in my script, I'd like the bat script to delete itself. This requires that the script know its name and then to use that name to delete itself. Is this possible?

like image 887
Berming Avatar asked Oct 03 '10 08:10

Berming


People also ask

Can a batch script delete itself?

You can just make it delete itself with del uninstaller. bat or del "%~f0" , where %~f0 represents the full path of the script.

Can a batch file delete files?

Batch file does delete files.

Can a batch file call itself?

You can create a batch program that calls itself. However, you must provide an exit condition.

How do you terminate a batch file?

Ctrl+C. One of the most universal methods of aborting a batch file, command, or another program while it's running is to press and hold Ctrl + C .


2 Answers

None of the existing answers provide a clean way for a batch file to delete itself and exit without any visible error message.

Simply including del "%~f0" does delete the script, but it also results in an ugly "The batch file cannot be found." error message.

If it is OK for the script to close the parent CMD process (the console window), then the following works fine without any error message:

del "%~f0"&exit

But it is a bit more complicated if you want the script to delete itself and exit without closing the parent CMD process, and without any error message.

Method 1: Start a second process that runs within the same console window that actually performs the delete. The EXIT /B is probably not necessary, but I put it in to maximize the probability that the batch script will close before the STARTed process attempts to delete the file.

start /b "" cmd /c del "%~f0"&exit /b

Method 2: Create and transfer control to another temp batch file that deletes itself as well as the caller, but don't use CALL, and redirect stderr to nul.

>"%~f0.bat" echo del "%~f0" "%~f0.bat"
2>nul "%~f0.bat"
like image 123
dbenham Avatar answered Sep 28 '22 15:09

dbenham


If I'm not mistaken, %0 will be the path used to call the batch file.

like image 39
JoshD Avatar answered Sep 28 '22 16:09

JoshD