This tutorial demonstrates how to delete files and folders using DOS commands, as well as how to accomplish this task using batch scripts.

Dos comamdn to delete files and folders

To delete a file, you can use the rm command.

rm file

To forcefully remove a file, you can use the -rf option.

rm -rf file

To delete a folder, utilize the rd command, which is an alias for the RMDIR command.

rd folder

This command prompts for confirmation before deletion and removes the folder along with its files. If the folder contains subfolders, an error is thrown. To delete a folder and its subfolders, use the /s option.

rd /s  folder

The /s option deletes the folder and its subfolders. To delete a folder without confirmation, add the /q option.

rd /s /q  folder

Another command to delete a folder is del command.

del /s /q folder

Batch Script to Delete Files and Folders

The following code checks if a folder exists and removes it along with all files and subdirectories within it.

if exist folder ( rmdir /s/q folder )

Another method involves using a for loop to iterate through each file and subfolder inside a given directory and remove them.

for /d %%k in ("%folder%\*") do rmdir /s /q "%%i"

Below is an example batch script to delete a file and folder.

@echo off
setlocal

REM Set file and folder paths for this example
set "file=C:\file.txt"
set "folder=C:\mydir"

REM Remove a single file
rm -rf "%file%"

REM 1.First way, remove an folder and subfolders  using rmdir
if exist folder ( rmdir /s/q folder )


REM 1. Second way using for loop, remove an folder and subfolders
if exist folder (
  for /d %%k in ("%folder%\*") do rmdir /s /q "%%i"
)