Page 1 of 1
Best command to delete a file?
Posted: 29 Jun 2020 22:13
by Jer
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
Re: Best command to delete a file?
Posted: 01 Jul 2020 05:14
by anic17
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.
Re: Best command to delete a file?
Posted: 01 Jul 2020 09:51
by Compo
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:
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"
Re: Best command to delete a file?
Posted: 01 Jul 2020 11:11
by Jer
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