0
0
Linux CLIscripting~5 mins

rm -r (remove directories) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to delete folders and everything inside them on your computer. The rm -r command helps you remove directories and all their files and subfolders quickly and safely.
When you want to delete a folder with many files inside it to free up space.
When you need to remove a project folder that you no longer need.
When cleaning up temporary directories created during software builds.
When deleting old backup folders that are no longer useful.
When removing nested folders that cannot be deleted with simple commands.
Commands
Create a folder named 'test-folder' with a subfolder inside it to demonstrate removal.
Terminal
mkdir -p test-folder/subfolder
Expected OutputExpected
No output (command runs silently)
Create two empty files inside the folders to show that rm -r deletes files too.
Terminal
touch test-folder/file1.txt test-folder/subfolder/file2.txt
Expected OutputExpected
No output (command runs silently)
Remove the 'test-folder' directory and everything inside it recursively.
Terminal
rm -r test-folder
Expected OutputExpected
No output (command runs silently)
-r - Recursively remove directories and their contents
Check if the 'test-folder' still exists after removal to confirm deletion.
Terminal
ls test-folder
Expected OutputExpected
ls: cannot access 'test-folder': No such file or directory
Key Concept

If you remember nothing else from this pattern, remember: rm -r deletes a directory and all its contents safely and completely.

Common Mistakes
Running rm without -r on a directory
rm without -r cannot delete directories and will show an error.
Always use rm -r when you want to delete directories and their contents.
Using rm -r on the wrong directory by mistake
This deletes important files or folders permanently, causing data loss.
Double-check the directory name before running rm -r to avoid accidental deletion.
Not having proper permissions to delete the directory
rm -r will fail with a permission denied error if you lack rights.
Use sudo rm -r if you have admin rights and need to delete protected folders.
Summary
Use mkdir and touch to create folders and files for testing rm -r.
Run rm -r foldername to delete a directory and all its contents recursively.
Verify deletion by listing the folder; it should no longer exist.