DEV Community

alok-38
alok-38

Posted on

Pro Bash Tip: Preserve Hidden Files and README.md While Deleting Everything Else

Have you ever needed to clean up a project directory but didn’t want to lose your hidden files or the all-important README.md?

Let’s talk about a simple, safe, and powerful command-line trick to do just that — using find.

🧩 The Problem

Say you’ve built and compiled several binaries, created temporary files, or generated test outputs. You want to wipe everything except:

  • Hidden files (e.g., .git, .env, .gitignore)
  • README.md

But using something like rm * will delete almost everything — and it won’t touch hidden files, which can be misleading. You need a smarter, safer approach.

✅ The Solution

find . -maxdepth 1 ! -name '.*' ! -name 'README.md' ! -name '.' -exec rm -rf {} +

Enter fullscreen mode Exit fullscreen mode

🔍 Breakdown:

  • find . -maxdepth 1: Only search in the current directory (not recursively).
  • ! -name '.*': Don’t touch hidden files/directories.
  • ! -name 'README.md': Keep your documentation safe.
  • ! -name '.': Prevent deleting the current directory.
  • -exec rm -rf {} +: Delete everything else — files and folders.

Before:

$ ls -al
calculator  calculator.c  func  func.c  hello  hello.c  ...
.git  .gitignore  README.md

Enter fullscreen mode Exit fullscreen mode

After:

$ find . -maxdepth 1 ! -name '.*' ! -name 'README.md' ! -name '.' -exec rm -rf {} +
$ ls -al
.git  .gitignore  README.md

Enter fullscreen mode Exit fullscreen mode

🛡️ Safety Tip

Before running rm -rf, test the output with:

find . -maxdepth 1 ! -name '.*' ! -name 'README.md' ! -name '.' -exec echo {} +

Enter fullscreen mode Exit fullscreen mode

This prints the files that would be deleted.

Finally run:

find . -maxdepth 1 ! -name '.*' ! -name 'README.md' ! -name '.' -exec rm -rf {} +

Enter fullscreen mode Exit fullscreen mode

Top comments (0)