Skip to content

rm Command: Removing Files and Directories

Summary

The rm command is a fundamental Linux utility for removing files and directories. It provides a straightforward way to delete unwanted items from your system. Use with caution, as deleted files are typically not recoverable via conventional means.

Introduction

The rm command is the primary tool for deleting files and directories in Linux. Its syntax is simple: rm [options] file1 file2 ... directory1 directory2 .... By default, rm removes files without prompting for confirmation. It's crucial to double-check your targets before executing rm, especially with wildcard characters.

Use case and Examples

Deleting a single file

rm myfile.txt
This command removes the file named myfile.txt from the current directory.

Deleting multiple files

rm file1.txt file2.txt file3.txt
This command removes file1.txt, file2.txt, and file3.txt from the current directory.

Deleting an empty directory

rm -d mydirectory
This command removes the empty directory named mydirectory. The -d flag is required to remove directories with rm. An alternative is to use rmdir mydirectory.

Deleting a directory and its contents recursively (USE WITH CAUTION!)

rm -r mydirectory
This command recursively removes the directory mydirectory and all its contents (files and subdirectories). This is a powerful command and can be dangerous if used incorrectly. Double check before using this command.

Deleting files interactively

rm -i file1.txt file2.txt
This command prompts for confirmation before deleting each file. You'll need to type y for yes or n for no for each file.

Forcing the removal of a write-protected file

rm -f file1.txt
This command forces the removal of file1.txt, even if you don't have write permissions on the file (assuming you have sufficient permissions on the parent directory).

Commonly used flags

Flag Description Example
-f or --force Ignores nonexistent files and arguments, never prompts. This is useful for scripting where you don't want errors to halt execution. rm -f non_existent_file.txt
-i or --interactive Prompts before every removal. rm -i myfile.txt
-r or -R or --recursive Removes directories and their contents recursively. Use with extreme caution. rm -r mydirectory
-d or --dir Removes empty directories. Equivalent to rmdir. rm -d empty_directory
-v or --verbose Shows what is being done. Prints the name of each file before removing it. rm -v myfile.txt
--one-file-system When removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument. rm -r --one-file-system /path/to/directory


Share on Share on

Comments