Linux – How to simply remove everything from a directory on Linux

command-line-interfacelinux

How to simply remove everything from a current or specified directory on Linux?

Several approaches:

  1. rm -fr *
    rm -fr dirname/*
    Does not work — it will leave hidden files — the one's that start with a dot, and files starting with a dash in current dir, and will not work with too many files

  2. rm -fr -- *
    rm -fr -- dirname/*
    Does not work — it will leave hidden files and will not work with too many files

  3. rm -fr -- * .*
    rm -fr -- dirname/* dirname/.*
    Don't try this — it will also remove a parent directory, because ".." also starts with a "."

  4. rm -fr * .??*
    rm -fr dirname/* dirname/.??*
    Does not work — it will leave files like ".a", ".b" etc., and will not work with too many files

  5. find -mindepth 1 -maxdepth 1 -print0 | xargs -0 rm -fr
    find dirname -mindepth 1 -maxdepth 1 -print0 | xargs -0 rm -fr
    As far as I know correct but not simple.

  6. find -delete
    find dirname -delete
    AFAIK correct for current directory, but used with specified directory will delete that directory also.

  7. find -mindepth 1 -delete
    find dirname -mindeph 1 -delete
    AFAIK correct, but is it the simplest way?

Best Answer

rm -fr * .*
Will work fine with at least GNU rm as it has special code to exclude "." and ".."

$ id
uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)
$ cd /tmp
$ mkdir rmtest
$ cd rmtest
$ touch .test
$ ls -la
total 8
drwxr-xr-x 2 nobody nogroup 4096 2009-08-19 15:37 .
drwxrwxrwt 7 root   root    4096 2009-08-19 15:37 ..
-rw-r--r-- 1 nobody nogroup    0 2009-08-19 15:37 .test
$ rm -rf .*
rm: cannot remove `.' or `..'
rm: cannot remove `.' or `..'
$ ls -la
total 8
drwxr-xr-x 2 nobody nogroup 4096 2009-08-19 15:37 .
drwxrwxrwt 7 root   root    4096 2009-08-19 15:37 ..
$

http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/remove.c#n440

FreeBSD rm man page says "It is an error to attempt to remove the files /, . or ..", so it probably works there too if you specify the force flag to ignore the error.

http://www.freebsd.org/cgi/man.cgi?query=rm&apropos=0&sektion=0&manpath=FreeBSD+7.2-RELEASE&format=html