Get a Pentest and security assessment of your IT network.

Cyber Security

Bash: Safe File Deletion with Wildcards

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

  1. Understand the Risk
  2. 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.

  3. Use find for Precision
  4. 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 by Name: Use the -name option. For example, to find all files ending in ‘.txt’:
    • find . -name "*.txt"
    • Find by Type: Use the -type f option to only find regular files (avoiding directories and other special file types). Use -type d for directories.
    • find . -type f -name "*.txt"
    • Find by Modification Time: Use the -mtime +7 option to find files modified more than 7 days ago (useful for cleanup scripts).
    • find . -type f -mtime +7
  5. Preview Deletions with -print
  6. 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.

  7. Execute Deletion with -delete
  8. 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.

  9. Safer Alternative: Use xargs rm
  10. 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
    • 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).
  11. Double-Check Before Running
  12. 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.

  13. Consider Backups
  14. Regular backups are essential. If you accidentally delete important files, a backup can save you from data loss.

Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation