Deleting All Files in a Folder in Linux

Popular:
LEVEL UP YOUR SERVER SETUP! APPLY AVA AND LAUNCH WITH A 15% DISCOUNT
USE PROMO:

Deleting all files in a folder in Linux is a common task for system administrators and developers. However, it must be done carefully to avoid unintentional data loss. In this guide, we’ll explore different methods to delete all files in a directory in your VPS, along with safety precautions to follow.

Understanding File Deletion in Linux

Linux provides multiple commands for file deletion, but they must be used with caution. The most commonly used commands include rm, find, and rsync. Let’s explore each method in detail.

Method 1: Using the rm Command

The

rm

(remove) command is the most direct way to delete files in a folder.

Delete All Files in a Folder (Without Deleting the Folder)

rm /path/to/folder/*

This command removes all files in the specified directory but does not delete subdirectories.

Delete All Files Including Hidden Files

rm -rf /path/to/folder/{*,.*}

This command ensures hidden files (those starting with

.

) are also removed.

Delete All Files and Subdirectories

rm -rf /path/to/folder/*

The

-r

flag ensures that directories inside the folder are also deleted, and the

-f

flag forces deletion without confirmation.

Caution When Using

rm

  • Always double-check the folder path before executing
    rm -rf

    .

  • Use
    ls

    to verify files before deletion:

    ls /path/to/folder
  • Avoid running
    rm -rf /

    as it can wipe the entire system.

Method 2: Using the find Command

The

find

command is a powerful alternative to delete files selectively.

Delete All Files in a Folder

find /path/to/folder -type f -delete

This command removes only files, leaving subdirectories intact.

Delete Files Based on Time (Older than 7 Days)

find /path/to/folder -type f -mtime +7 -delete

This command deletes files that haven’t been modified in the last 7 days.

Method 3: Using rsync to Empty a Folder

A safer way to clear a folder without deleting the folder itself:

rsync -a --delete empty_folder/ target_folder/

Here, empty_folder/ is an intentionally empty directory used to remove all files in target_folder/.

Method 4: Using shred for Secure Deletion

If you need to securely erase files to prevent recovery, use

shred

:

shred -u /path/to/folder/*

This overwrites files multiple times before deleting them.

Final Recommendations

  • Use
    rm -i

    for interactive deletion to confirm each file removal:

    rm -i /path/to/folder/*
  • Create backups before deletion, especially for critical data.
  • Use test directories to practice deletion commands before applying them to important files.

By following these methods and precautions, you can safely delete all files in a Linux folder while minimizing the risk of accidental data loss.