How to Use rm Command in Linux: Syntax and Examples
The
rm command in Linux is used to delete files and directories. Use rm filename to remove a file and rm -r directoryname to remove a directory and its contents recursively.Syntax
The basic syntax of the rm command is:
rm [options] file_or_directory
Here:
- rm: The command to remove files or directories.
- options: Flags to modify behavior, like
-rfor recursive deletion or-fto force deletion without prompts. - file_or_directory: The name of the file or directory you want to delete.
bash
rm [options] file_or_directory
Example
This example shows how to delete a file named example.txt and a directory named myfolder with all its contents.
bash
touch example.txt mkdir myfolder touch myfolder/file1.txt rm example.txt rm -r myfolder
Common Pitfalls
Common mistakes include:
- Trying to delete a directory without
-roption, which causes an error. - Using
rmwithout caution can delete important files permanently. - Not using
-fwhen scripting can cause prompts that stop automation.
Always double-check the file or directory name before running rm.
bash
rm myfolder
# Error: rm: cannot remove 'myfolder': Is a directory
rm -r myfolder
# Correct: deletes directory and contentsOutput
rm: cannot remove 'myfolder': Is a directory
Quick Reference
| Option | Description |
|---|---|
| -r | Remove directories and their contents recursively |
| -f | Force removal without confirmation prompts |
| -i | Prompt before every removal |
| -v | Verbose mode, shows files being removed |
Key Takeaways
Use
rm filename to delete a single file safely.Add
-r to delete directories and their contents recursively.Use
-f to force deletion without prompts, useful in scripts.Always double-check what you are deleting to avoid accidental data loss.
Use
-i option if you want confirmation before each deletion.