Linux / Unix: Find All Hidden Dot Directories and Delete

See all Bash/Shell scripting related FAQ
I need to clean up my backups stored on the nas server. I need to free up the disk space. How do I find out all hidden dot directories such as /nas01/backups/home/user/.gnome/, /nas01/backups/home/user/.gnome/ and so on and delete then in a single pass using Linux or Unix command line option? Please note that I do not want to delete nested hidden directories such as /nas01/backups/home/user/data/.xml, /nas01/backups/home/user/foo/bar/.level/.levle2/ and so on.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements find
Est. reading time 1 minutes
You can use the find command to find or locate files on a Linux or Unix system. The search is recursive in that it will search all subdirectories too. The syntax is:
Advertisement

find /path/to/search criteria action

Here’s an example find command using a search criterion and the default print action:

find /nas01/backups/home/user/ -name file-Name-here

To match only directories, use:

find /nas01/backups/home/user/ -type d -name file-Name-here -print0

To match only hidden dot directories, enter:
find /nas01/backups/home/user/ -type d -name ".*" -print0

To descend at most one levels of directories below the command line arguments pass the -maxdepth 1 option. This will avoid deleting nested directories:

find /nas01/backups/home/user/ -maxdepth 1 -type d -name ".*" -print0

Once satisfied with the result, use the xargs command to delete all hidden directories:

find .  -maxdepth 1 -type d -iname ".[^.]*" -print0 | xargs -I {} -0 rm -rvf "{}"

OR

find .  -maxdepth 1 -type d -iname ".*" -print0 | xargs -I {} -0 rm -rvf "{}"

🥺 Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🤠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

4 comments… add one
  • nick May 5, 2013 @ 20:03

    Won’t this, without maxdepth also delete directories higher than the specified (.* matches “..”)?

  • Casper May 5, 2013 @ 20:05

    Why not use -exec:

    find . -maxdepth 1 -type d -iname “.[^.]*” -exec rm -rvf “{}” \;

  • a reader May 5, 2013 @ 20:27

    why not use -delete:

    find -maxdepth 1 -type d -name “.[^.]*” -deletewe have got crammed

  • Saenthan Jul 5, 2013 @ 6:14

    ls -al

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.