29

How do I delete everything in a directory, including hidden files and directories?

Right now, I use the following:

rm -rf *
rm -rf .*
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

8 Answers8

19

Simple and straight forward:

find -delete 

Includes directories and hidden files. At least gnu-find knows -delete, your find may differ.

user unknown
  • 10,482
11

The best answer is: Don't do that. Recursively remove the directory itself, then recreate it as an empty directory. It's more reliable and easier for other people to understand what you're trying to do. When you re-create the directory it may have a different owner, group and permissions. If those are important be careful. Also, if any running programs have open file handles (descriptors) on the directory then you won't want to remove it. If none of those special cases apply, then it's simpler to remove the entire directory.

  • 8
    So how is that more easy. 'Be careful' isn't an answer. I wouldn't understand why somebody deletes a directory and rebuilds it again. – user unknown Mar 21 '11 at 03:36
  • I added the phrase "as an empty directory", perhaps that's more clear. – Chris Quenelle Jul 02 '13 at 22:49
  • 3
    No, it doesn't explain why you delete a directory and recreate it then. To the things to consider belongs, btw., date/time of creation too. – user unknown Jul 02 '13 at 23:14
  • 3
    If that directory is the current working directory of some process, you may run into problems. Also, if you remove the directory, you remove information about its permissions and ownership. –  Jul 03 '13 at 00:03
  • What if the directory is a mount point? What if you don't have permission to remove the directory itself? – AtomHeartFather Jan 20 '22 at 19:08
  • If it's a mount point then you can't remove it. Good point. – Chris Quenelle Jan 21 '22 at 20:55
9
rm -rf -- * .[!.]* ..?*

Each of the three pattern expands to itself if it matches nothing, but that's not a problem here since we want to match everything and rm -f ignored nonexistent arguments.

Note that .* would match ...

5

Assuming bash 4+:

shopt -s dotglob
rm -rf -- *
##or:
rm -rf ./*

With dotglob enabled, * expands to all files and directories, even those that begin with . - but doesn't expand to . and .., so it is safe to use with rm.

evilsoup
  • 6,807
  • 3
  • 34
  • 40
2

if you are in the directory:

cd .. && rm -rf dir && mkdir dir && cd dir

otherwise:

rm -rf /path/to/dir && mkdir /path/to/dir

2

Oh my Zsh

rm -rf (.|)*

Again, this is for Zsh only.

phunehehe
  • 20,240
1

How about using find. I think this is generally a good choice, when you have to dig through sub-directories.

find . -type f -exec rm {} \;
wag
  • 35,944
  • 12
  • 67
  • 51
slashdot
  • 666
-2

Try rm -rf *?*. This will delete normal and hidden files.

gladimdim
  • 257