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.
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.
The rm
(remove) command is the most direct way to delete files in a folder.
rm /path/to/folder/*
This command removes all files in the specified directory but does not delete subdirectories.
rm -rf /path/to/folder/{*,.*}
This command ensures hidden files (those starting with .
) are also removed.
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.
rm
rm -rf
.ls
to verify files before deletion:ls /path/to/folder
rm -rf /
as it can wipe the entire system.The find
command is a powerful alternative to delete files selectively.
find /path/to/folder -type f -delete
This command removes only files, leaving subdirectories intact.
find /path/to/folder -type f -mtime +7 -delete
This command deletes files that haven’t been modified in the last 7 days.
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/.
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.
rm -i
for interactive deletion to confirm each file removal:rm -i /path/to/folder/*
By following these methods and precautions, you can safely delete all files in a Linux folder while minimizing the risk of accidental data loss.