How to Delete a Directory in Linux: Simple Commands
To delete an empty directory in Linux, use the
rmdir command followed by the directory name. To delete a directory and all its contents, use rm -r directory_name which removes the directory recursively.Syntax
The basic commands to delete directories in Linux are:
rmdir directory_name: Deletes an empty directory.rm -r directory_name: Deletes a directory and all its contents recursively.
Here, directory_name is the name or path of the directory you want to delete.
bash
rmdir directory_name rm -r directory_name
Example
This example shows how to delete an empty directory and a directory with files inside.
bash
mkdir testdir mkdir testdir/emptydir mkdir testdir/fulldir touch testdir/fulldir/file1.txt rmdir testdir/emptydir rm -r testdir/fulldir ls testdir
Output
(emptydir deleted)
(fulldir deleted recursively)
(empty output, no directories left inside testdir)
Common Pitfalls
Common mistakes when deleting directories include:
- Trying to delete a non-empty directory with
rmdir, which only works on empty directories. - Forgetting to use
-rwithrmto delete directories recursively. - Accidentally deleting important files by running
rm -rwithout checking the directory contents.
Always double-check the directory contents before deleting.
bash
rmdir mydir
# Fails if mydir is not empty
rm -r mydir
# Correct way to delete non-empty directoryOutput
rmdir: failed to remove 'mydir': Directory not empty
# rm -r deletes directory and contents silently
Quick Reference
| Command | Description |
|---|---|
| rmdir directory_name | Delete an empty directory |
| rm -r directory_name | Delete directory and all contents recursively |
| rm -rf directory_name | Force delete directory and contents without prompts (use carefully) |
Key Takeaways
Use
rmdir only for empty directories.Use
rm -r to delete directories with files inside.Always check directory contents before deleting to avoid data loss.
Add
-f to rm -r to force deletion without confirmation.Be cautious with recursive delete commands to prevent accidental removal.