Delete a directory and its files using command line but don't throw error if it doesn't exist
WindowsBatch FileCmdWindows Problem Overview
I need a Windows command to delete a directory and all its containing files but I do not want to see any errors if the directory does not exist.
Windows Solutions
Solution 1 - Windows
Redirect the output of the del
command to nul. Note the 2
, to indicate error output should be redirected. See also this question, and especially the tech doc Using command redirection operators.
del {whateveroptions} 2>null
Or you can check for file existence before calling del
:
if exist c:\folder\file del c:\folder\file
Note that you can use if exist c:\folder\
(with the trailing \
) to check if c:\folder
is indeed a folder and not a file.
Solution 2 - Windows
Either redirect stderr to nul
rd /q /s "c:\yourFolder" 2>nul
Or verify that folder exists before deleting. Note that the trailing \
is critical in the IF condition.
if exist "c:\yourFolder\" rd /q /s "c:\yourFolder"
Solution 3 - Windows
For me on Windows 10 the following is working great:
if exist <path> rmdir <path> /q /s
q
stands for "delete without asking" and s
stands for "delete all subfolders and files in it".
And you can also concatinate the command:
(if exist <path> rmdir <path> /q /s) && <some other command that executes after deleting>
Solution 4 - Windows
You can redirect stderr to nul
del filethatdoesntexist.txt 2>nul
Solution 5 - Windows
The above comes up with Y or N in the prompt. So, I used the following instead and it works perfectly.
if exist cddd rmdir cddd
Hope this helps someone.
Cheers.