0
0
Linux-cliHow-ToBeginner · 3 min read

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 -r for recursive deletion or -f to 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 -r option, which causes an error.
  • Using rm without caution can delete important files permanently.
  • Not using -f when 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 contents
Output
rm: cannot remove 'myfolder': Is a directory
📊

Quick Reference

OptionDescription
-rRemove directories and their contents recursively
-fForce removal without confirmation prompts
-iPrompt before every removal
-vVerbose 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.