How to Delete Files in Linux

Linux provides multiple ways to remove files, whether it's a single file, multiple files, or entire directories. Below are different methods for safely deleting files.


1. Deleting a File with rm (Remove Command)

The rm command is the standard way to delete files.


A. Remove a Single File

rm filename.txt

Deletes filename.txt from the current directory.


B. Remove Multiple Files

rm file1.txt file2.txt file3.txt

Deletes multiple files at once.


C. Force Delete Without Confirmation (-f)

rm -f filename.txt

-f (force) removes the file without prompting for confirmation, even if it's write-protected.

2. Deleting Files in a Directory

A. Remove All Files in a Directory (Keep Subdirectories)

rm /path/to/directory/*

Deletes all files in /path/to/directory/ but keeps subdirectories.


B. Remove Files and Subdirectories Recursively (-r Option)

rm -r /path/to/directory/

-r (recursive) deletes all files and subdirectories within the directory.

Use with caution, as this action cannot be undone.

C. Force Delete a Directory Without Prompt (-rf Option)

rm -rf /path/to/directory/

-r → Recursively removes directories and files.

-f → Skips confirmation prompts.

Warning: This command permanently deletes everything in the directory.


3. Using unlink (Alternative to rm)

The unlink command can remove a single file, but it does not support deleting multiple files or directories.


unlink filename.txt

Unlike rm, unlink does not prompt for confirmation and does not work on directories.


4. Deleting Files by Pattern (Using Wildcards * and ?)

A. Delete All .txt Files

rm *.txt

Removes all .txt files in the current directory.


B. Delete Files That Start with "log_"

rm log_*

Deletes all files that begin with log_.


C. Delete Files Containing a Specific Word

rm *error*.log

Deletes all .log files that have “error” in their name.


5. Securely Deleting a File (Prevent Recovery)

If you want to permanently delete a file and make it unrecoverable, use:

shred -u filename.txt

-u → Deletes the file after overwriting it multiple times.

Useful for removing sensitive data.

For a more secure wipe, use:

shred -zvu filename.txt

-z → Overwrites with zeroes for extra security.

-v → Shows the process while running.

-u → Removes the file after shredding.

Conclusion

 - Use rm for basic file deletion.

 - Use rm -r for deleting directories and their contents.

 - Use unlink to remove a single file.

 - Use shred to securely delete files so they cannot be recovered.


 - Be careful when using rm -rf, as deleted files cannot be restored! 

Comments

Popular posts from this blog

Absolute and relative path in HTML pages

Errors

goto PHP operator