Best command to delete a file?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Best command to delete a file?

#1 Post by Jer » 29 Jun 2020 22:13

I see this in a post: del file.tmp 2>nul

I delete temporary files using this syntax: IF EXIST "%tempfileID%" DEL "%tempfileID%"
Is there a preferred way to do this?
Thanks.
Jerry

anic17
Posts: 1
Joined: 01 Jul 2020 05:11

Re: Best command to delete a file?

#2 Post by anic17 » 01 Jul 2020 05:14

You can do it like that:

Code: Select all

if exist "%TMP%\*.*" erase "%TMP%" /s /q /f 2>nul 1>nul
Why do you want to make it in a different way? This works fine.

Compo
Posts: 600
Joined: 21 Mar 2014 08:50

Re: Best command to delete a file?

#3 Post by Compo » 01 Jul 2020 09:51

It's a matter of opinion really.

I believe that you should be polite, i.e ask for an action only if its needed, so my preference is to see if the file exists prior to asking for it to be deleted.

However checking if the file exists, is an action in itself, so some would see it as no less efficient to action a delete, and just redirect any StdErr message to the NUL device.

It is also, worth noting that with the redirected error, if the file exists, but the delete command itself has an issue, you'll be unaware of it if redirecting the message:

Code: Select all

@Del "%tempFileID%" 2> NUL
Whereas, here you still have an option to see isome error output to the console:

Code: Select all

@If Exist "%tempfileID%" Del "%tempFileID%"
However using the check above, it is possible that `If Exist` finds a matching named directory, and obviously for that, the `Del` command would fail. So to prevent that from being a possible reason for an StdErr message, you could use a different method of checking existence of a file only:

Code: Select all

@For %%G In ("%tempfileID%") Do @If "%%~aG" Lss "d" If "%%~aG" GEq "-" Del "%%G"
And of course, to give a greater chance of success, the delete command has additional options too:

Code: Select all

@For %%G In ("%tempfileID%") Do @If "%%~aG" Lss "d" If "%%~aG" GEq "-" Del /A /F "%%G"

Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Re: Best command to delete a file?

#4 Post by Jer » 01 Jul 2020 11:11

Thanks for both for the explanations and examples of redirection of the error message.
The shorter and safe method, del "%tempFileID%" 2> NUL is the one I'll use.

Batch tools in my never-ending project write temporary files to get to the end product,
and file removal is done after each temporary file has served its purpose.
Jer

Post Reply