[Linux] A Complete Guide to Deleting Files and Directories with the rm Command

目次

Overview

The rm (remove) command is the standard utility for deleting files and directories that are no longer needed in a Linux system.

Unlike the trash can feature in graphical user interfaces (GUI), data deleted with the rm command cannot be restored using standard functions. Therefore, extreme caution is required when executing it. This command is frequently used for organizing logs in server management or cleaning up directories before deployment.


Specifications (Arguments and Options)

Syntax

rm [options] [file_or_directory_name]

Main Arguments and Options

OptionDescription
-fForce. Removes files without prompting for confirmation and ignores non-existent files.
-iInteractive. Prompts for confirmation before every removal.
-r / -RRecursive. Removes directories and their contents (subdirectories and files) completely.
-dRemoves empty directories (equivalent to the rmdir command).
-vVerbose. Displays the name of each file as it is removed.
--no-preserve-rootDisables the protection for the root directory (/). (Used only in extreme testing scenarios).

Basic Usage

The most basic usage is to remove a single file without any options.

Command

# Deletes old_config.conf in the current directory
rm old_config.conf

Execution Result

No output is displayed on success. An error is shown if the file does not exist.

(No output)

Practical Commands

Forcefully Deleting a Directory and Its Contents

This combination is often used to batch delete temporary files in development environments or application cache directories. It deletes contents recursively (-r) without showing a confirmation screen (-f).

# Deletes the logs directory and all files within it
rm -rf ./logs/

Confirming Before Deletion (Safe Deletion)

To prevent accidental operations, this prompts “Are you sure you want to delete this?” for each target. This is recommended when handling important configuration files.

# Prompt for confirmation before deleting a critical backup file
rm -i production_db_backup.sql

Example prompt:

rm: remove regular file 'production_db_backup.sql'? y

Note: Entering y followed by Enter deletes the file; n cancels the operation.

Deleting a Directory with Itemized Confirmation

Used when you want to delete a directory (-r) but wish to verify each item (-i) inside it as you go.

# Deletes the user_data directory while confirming each file individually
rm -ri ./user_data/

Example execution flow:

rm: descend into directory './user_data/'? y
rm: remove regular file './user_data/user_01.dat'? y
rm: remove regular file './user_data/user_02.dat'? n
rm: remove directory './user_data/'? n

Customization Points

  • Target Paths: Adjust ./logs/ or production_db_backup.sql to match your specific target.
  • Option Selection: Use -f in automation scripts, but consider aliasing rm to rm -i for manual terminal operations to increase safety.
  • Multiple Targets: You can specify multiple files by separating them with spaces, such as rm file1.txt file2.txt.

Important Notes

  • Irreversible Action: Files deleted with rm do not move to a “Recycle Bin.” The links on the disk are immediately removed. Recovery is difficult without a backup.
  • The Danger of rm -rf /: Executing this on the root directory will destroy the entire system. While modern distributions have built-in protections, never use the --no-preserve-root option unless for specific validation purposes.
  • Wildcard Risks: When using rm * or rm *.log, there is a risk of matching and deleting unintended files. It is best practice to run ls *.log first to verify the targets.
  • Permission Errors: Attempting to delete files in a directory for which you do not have write permissions will result in a Permission denied error. In such cases, sudo is required.

Advanced Application

Combining with the find Command to Delete Old Files

This is a modern, safe method to search for and delete files like log files that have exceeded a specific age without using complex pipes.

# Search for and delete files ending in .log that haven't been updated in over 30 days
find . -name "*.log" -mtime +30 -delete

Conclusion

Warning: The -rf option is powerful; a mistake in path specification can lead to system destruction. Always use absolute paths or verify relative paths carefully.

Best Use Cases: Organizing unnecessary files on a server, deleting temporary files via scripts, and restructuring directory hierarchies.

Key Strategy: For those unfamiliar with the environment, actively use the -i option to prevent accidental data loss.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次