DEL *this* file (whatever its name) in Batch File

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
stephjo
Posts: 10
Joined: 03 Feb 2014 02:39

DEL *this* file (whatever its name) in Batch File

#1 Post by stephjo » 12 Nov 2020 08:09

Hi DOS enthusiasts,

I've got an image analysis software that spits out batch files and often changes the content and the name(!) and the location of the batch file for various reasons. So, very often, if I have a "DEL" command at the end of the file, the command doesn't execute because I don't have the name right and/or location right.

It'd be superb if there was a way to have a command at the end of these batch files that says

del /q whatever_this_batch_file_name.bat

How do I do this?

Thank you,
-Steph

ShadowThief
Expert
Posts: 993
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: DEL *this* file (whatever its name) in Batch File

#2 Post by ShadowThief » 12 Nov 2020 08:32

%0 is the full path of the script that is currently running.

Code: Select all

del %0

aGerman
Expert
Posts: 4008
Joined: 22 Jan 2010 18:01
Location: Germany

Re: DEL *this* file (whatever its name) in Batch File

#3 Post by aGerman » 12 Nov 2020 10:19

ShadowThief wrote:
12 Nov 2020 08:32
%0 is the full path of the script
Nope. %0 contains how the script was called. Consider to have a "FOO.bat". From within a command prompt you could just enter FOO to run it. But in this case %0 expands to only FOO where deleting would fail.
To expand it to the full path you have to use "%~f0" (including the quotes to protect you from spaces and special characters).

Steffen

ShadowThief
Expert
Posts: 993
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: DEL *this* file (whatever its name) in Batch File

#4 Post by ShadowThief » 12 Nov 2020 13:58

Horrifyingly, I've spent almost the last decade tab-completing the name of the script so I've literally never run into this problem. :shock:

koko
Posts: 31
Joined: 13 Oct 2016 00:40

Re: DEL *this* file (whatever its name) in Batch File

#5 Post by koko » 13 Nov 2020 00:27

aGerman wrote:
12 Nov 2020 10:19
ShadowThief wrote:
12 Nov 2020 08:32
%0 is the full path of the script
Nope. %0 contains how the script was called. Consider to have a "FOO.bat". From within a command prompt you could just enter FOO to run it. But in this case %0 expands to only FOO where deleting would fail.
To expand it to the full path you have to use "%~f0" (including the quotes to protect you from spaces and special characters).
Thought I'd just mention (though obvious) this works while delayed expansion is disabled though if it's later enabled requires getting past endlocal and some form of escaping for characters such as exclamation points and carets (which itself can be a PITA until one finds suitable methods :p).

Post Reply