TL;DR
Deleting files using wildcards in Bash can be dangerous if you’re not careful. This guide shows how to use find and rm safely, preview your deletions, and avoid accidental data loss.
Solution Guide
- Understand the Risk
- Use
findfor Precision - Find by Name: Use the
-nameoption. For example, to find all files ending in ‘.txt’: - Find by Type: Use the
-type foption to only find regular files (avoiding directories and other special file types). Use-type dfor directories. - Find by Modification Time: Use the
-mtime +7option to find files modified more than 7 days ago (useful for cleanup scripts). - Preview Deletions with
-print - Execute Deletion with
-delete - Safer Alternative: Use
xargs rm - Explanation:
-print0: Prints filenames separated by null characters, which is safer for filenames with spaces or special characters.xargs -0: Reads input separated by null characters.rm -f: Forcefully deletes the files (use with caution).- Double-Check Before Running
- Consider Backups
Bash wildcards (like *) expand to match filenames. If you make a mistake in your pattern, you could delete files you didn’t intend to. For example, rm * deletes everything in the current directory.
The find command is much safer because it lets you specify exactly which files to delete based on various criteria (name, type, size, etc.).
find . -name "*.txt"
find . -type f -name "*.txt"
find . -type f -mtime +7
Before deleting anything, always preview the files that will be affected. Use the -print option with find.
find . -type f -name "*.txt" -print
This shows you a list of the files that would be deleted without actually deleting them.
Once you’re confident, use the -delete option to delete the files. Be extremely careful!
find . -type f -name "*.txt" -delete
Important: The -delete action is performed immediately after finding a match. There’s no undo.
For more control, pipe the output of find to xargs rm. This allows you to review the command before execution and handle filenames with spaces or special characters correctly.
find . -type f -name "*.txt" -print0 | xargs -0 rm -f
Before running any rm command, especially with wildcards or xargs, carefully review the full command and make sure it will only delete the files you intend to remove.
Regular backups are essential. If you accidentally delete important files, a backup can save you from data loss.

