rm -r (recursive remove for directories)
The rm -r (or rm -R) command is used to remove directories and all of their contents recursively. It is an extremely powerful and potentially destructive command, as it can wipe out entire directory trees with no confirmation by default.
Example 1: Remove a directory and all its contents
# Recursively remove the 'old_project' directory and everything inside it
rm -r old_project
Explanation: This command will delete the old_project directory, all files within it, and all subdirectories and their files. This action is permanent.
Example 2: Recursive and interactive removal
# Recursively remove the 'temp_files' directory, prompting for each file and directory
rm -ri temp_files/
Explanation: Combining -r (recursive) with -i (interactive) provides a safer way to delete directories. The command will traverse the directory and ask for confirmation before deleting every single item, which can be tedious but prevents mistakes.
Example 3: Recursive and verbose removal
# Recursively remove the 'build_cache' directory and show each item as it is deleted
rm -rv build_cache/
Explanation: The -rv options will recursively delete the directory while printing a line for each file and subdirectory as it is removed. This is useful for observing the progress of the deletion.
Example 4: Removing multiple directories at once
# Recursively remove two separate directories, 'test1' and 'test2'
rm -r test1 test2
Explanation: You can specify multiple directory names to rm -r to delete all of them and their respective contents in a single command.
Example 5: Deleting contents of a directory but not the directory itself
# Remove all files and subdirectories inside 'downloads' but leave 'downloads' itself
rm -r downloads/*
Explanation: The wildcard * expands to all files and directories within downloads. This command effectively empties a directory of its contents while preserving the parent directory. Hidden files (starting with a dot) will not be removed.
Example 6: Removing a directory with a space in its name
# Recursively remove the directory named 'Obsolete Project'
rm -r "Obsolete Project"
Explanation: If a directory's name contains spaces or special characters, it must be enclosed in quotes to be correctly interpreted by the shell as a single argument for the rm command.
Example 7: Removing all .bak files from a directory tree
# Find and remove all files ending with .bak within the current directory and its subdirectories
find . -name "*.bak" -exec rm {} \;
Explanation: While not a direct use of rm -r, this is a common and safer pattern. The find command locates all files matching the pattern (*.bak), and for each one found, it executes rm. This is more precise than a broad rm -r command.