Page 1 of 1
DEL *this* file (whatever its name) in Batch File
Posted: 12 Nov 2020 08:09
by stephjo
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
Re: DEL *this* file (whatever its name) in Batch File
Posted: 12 Nov 2020 08:32
by ShadowThief
%0 is the full path of the script that is currently running.
Re: DEL *this* file (whatever its name) in Batch File
Posted: 12 Nov 2020 10:19
by aGerman
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
Re: DEL *this* file (whatever its name) in Batch File
Posted: 12 Nov 2020 13:58
by ShadowThief
Horrifyingly, I've spent almost the last decade tab-completing the name of the script so I've literally never run into this problem.
Re: DEL *this* file (whatever its name) in Batch File
Posted: 13 Nov 2020 00:27
by koko
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).