rm -r vs rm -rf: delete a folder and its contents safely
What rm -r and rm -rf do, how they differ, how to delete a folder with the least risk, and the mistakes that cause data loss.
rm does not remove folders by default. Add -r to remove a folder and everything inside it. Add -f to skip all questions and ignore missing files. There is no recycle bin, so check the path before you press Enter.
A safer way to delete a folder
- Look at what you are about to delete: ls -la foldername.
- Delete it with a prompt: rm -rI foldername. It asks once before removing recursively.
- Use rm -rf foldername only when you are sure of the exact name.
- Never put a variable in the path unless you know it is not empty.
Commands you can copy
rm -r foldernamerm -rf foldernamerm -rI foldernamerm -ri foldernamermdir foldernamerm -- -fooWhat the options mean
- -r, -R, --recursive
- Removes directories and their contents. Without it, rm refuses to delete a folder.
- -f, --force
- Ignores files that do not exist and never prompts. It is what makes rm -rf silent and fast, and dangerous.
- -i and -I
- -i prompts before every removal. -I prompts once before removing more than three files or when removing recursively, which is less noisy.
- -d, --dir
- Removes empty directories, like rmdir.
- The root protection
- --preserve-root is the default, so rm -rf / is blocked. That protection does not cover everything: a wildcard such as /* or a wrong path is not stopped.
- Can I get the files back?
- A removed file might be recoverable with special tools, but you should not count on it. GNU rm recommends shred if you need the data gone for good.
- Permission denied
- You do not own the folder or its parent. Check with ls -ld. Use sudo only if you are certain of the path; see chmod and chown for fixing ownership instead.
Questions about rm -r and rm -rf
- What is the difference between rm -r and rm -rf?
- -r removes a folder recursively and still asks about some files, such as write-protected ones. -rf never asks and ignores missing files.
- How do I delete a folder with the least risk?
- Run ls on it first, then rm -rI so you are asked once. Avoid wildcards and unset variables in the path.
- Does rm -rf move files to the trash?
- No. The files are unlinked immediately and there is no trash.
- How do I remove a folder that is not empty with rmdir?
- You cannot. rmdir only removes empty folders. Use rm -r.