Folder Management
File Deletion
Computer Troubleshooting
Tech Tips
Operating Systems

How to delete a non-empty folder: rmdir /s on Windows, rm -rf on Linux

Codemia Knowledge Hub ·

To delete a non-empty folder, use rmdir /s /q C:\path\to\folder in Windows Command Prompt or rm -rf /path/to/folder on macOS and Linux. In Python, use shutil.rmtree(); in Node.js, use fs.rmSync() with the recursive option. Each removes the directory and everything inside it, including nested subdirectories and files.

Plain rmdir on Unix-like systems and basic Remove-Item in PowerShell refuse to delete directories that still contain files. That is a safety measure, so you need a different command or flag when you really want to remove a whole tree.

Windows

Command Prompt: rmdir /s /q

cmd
rmdir /s /q C:\path\to\folder
  • /s: removes the directory and all files and subdirectories inside it
  • /q: quiet mode, suppresses the confirmation prompt

rmdir /s may fail if paths in the tree exceed 260 characters. Use the \\?\C:\path\to\folder prefix for long path support, or use PowerShell, which handles long paths better.

PowerShell: Remove-Item -Recurse -Force

powershell
Remove-Item -Path "C:\path\to\folder" -Recurse -Force
  • -Recurse: deletes all child items
  • -Force: removes hidden and read-only files without prompting

Wildcards let you delete several directories at once:

powershell
Remove-Item -Path "C:\temp\build_*" -Recurse -Force

Linux and macOS

rm -rf

bash
rm -rf /path/to/directory
  • -r (recursive): descend into subdirectories and delete everything inside
  • -f (force): skip confirmation prompts and ignore nonexistent files

Nothing goes to a trash folder. Deletion is permanent and immediate.

Deleting only directories that match a pattern

bash
find /path/to/parent -type d -name "cache_*" -exec rm -rf {} +

This finds all directories whose names start with cache_ and removes them recursively, leaving the rest intact.

Moving to the trash instead

If you want to be able to recover the folder, use a trash utility:

bash
1# Install trash-cli (Linux)
2sudo apt install trash-cli
3trash-put /path/to/directory
4
5# macOS (using Homebrew)
6brew install trash
7trash /path/to/directory

In code

Python: shutil.rmtree

python
import shutil

shutil.rmtree("/path/to/directory")

shutil.rmtree walks the tree from the bottom up, removing files and then directories. It raises FileNotFoundError if the path does not exist, so guard it when the directory may already be gone:

python
1import shutil
2import os
3
4path = "/path/to/directory"
5if os.path.exists(path):
6    shutil.rmtree(path)

On Windows it raises PermissionError on read-only files by default. An onerror handler can clear the read-only flag and retry:

python
1import shutil
2import stat
3import os
4
5def handle_readonly(func, path, exc_info):
6    os.chmod(path, stat.S_IWRITE)
7    func(path)
8
9shutil.rmtree("/path/to/directory", onerror=handle_readonly)

Node.js: fs.rmSync

javascript
const fs = require('fs');

fs.rmSync('/path/to/directory', { recursive: true, force: true });

force prevents an error if the directory does not exist. The asynchronous version:

javascript
const fs = require('fs/promises');

await fs.rm('/path/to/directory', { recursive: true, force: true });

Java: Files.walk in reverse order

java
1import java.io.IOException;
2import java.nio.file.*;
3import java.util.Comparator;
4
5Path directory = Paths.get("/path/to/directory");
6
7Files.walk(directory)
8     .sorted(Comparator.reverseOrder())
9     .forEach(path -> {
10         try {
11             Files.delete(path);
12         } catch (IOException e) {
13             throw new RuntimeException("Failed to delete: " + path, e);
14         }
15     });

Files.walk traverses the tree depth-first. Sorting in reverse order deletes files before their parent directories.

Comparison

MethodPlatformRecoverableHandles Read-Only
rm -rfLinux, macOSNoYes (with force)
trash-put / trashLinux, macOSYes (trash)No
rmdir /s /qWindows CMDNoNo
Remove-Item -Recurse -ForceWindows PowerShellNoYes
shutil.rmtree()Python (cross-platform)NoWith error handler
fs.rmSync({recursive: true})Node.js (cross-platform)NoYes (with force)
Files.walk + Files.deleteJava (cross-platform)NoNo

Permission denied and locked files

On Linux and macOS you can get "Permission denied" even with -f when you do not own the files or the directory has restricted permissions:

bash
1# Change ownership first (requires sudo)
2sudo chown -R $(whoami) /path/to/directory
3rm -rf /path/to/directory
4
5# Or run rm with sudo directly
6sudo rm -rf /path/to/directory

On Windows, running processes may lock files. Close the application using the file, or use a tool like Handle from Sysinternals to find which process holds the lock.

Avoiding accidental damage with rm -rf

A typo can wipe the filesystem. A misplaced space or variable expansion in a script can turn the command into rm -rf / or rm -rf /*. Double-check paths and quote variables: rm -rf "${TARGET_DIR}" rather than an unquoted expansion.

Empty variables are catastrophic. If $DIR is empty, rm -rf $DIR/ expands to rm -rf /. Validate variables before using them in destructive commands:

bash
if [ -n "$DIR" ] && [ -d "$DIR" ]; then
    rm -rf "$DIR"
fi

Symlinks behave differently with a trailing slash. rm -rf on a symlink removes the link itself, not the target directory. But rm -rf symlink/ may follow the link and delete the target's contents. Behavior varies across systems.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Interview Questions practice on Codemia

Over 11,000 interview practice questions for 300+ companies, searchable by company and role.

Browse interview questions