Alex Rivera | Logout

Finding empty directories

Asked 2010-05-11T12:57:25.950
140

I need to find empty directories for a given list of directories. Some directories have directories inside it.

If inside directories are also empty I can say main directory is empty otherwise it's not empty.

How can I test this?

For example:

A>A1(file1),A2 this is not empty beacuse of file1
B>B1(no file) this is empty
C>C1,C2 this is empty
Edit
Report

4 Answers

336

The following will remove all empty directories (those with no children). As it does so depth-first (bottom-up), it will remove directories with only (empty) directories as children. Beware that, in find, the order of arguments matters.

find testdir -depth -type d -empty -delete

Drop -delete to see the files and directories matched, however note that because of -depth, parent dirs that would become empty will not be listed (beware that -depth is implied by -delete in some find implementations). Remove the -type d if you would to also like to delete empty files.

For example:

$ mkdir -p testdir/foo/bar/baz; touch testdir/foo/afile.txt

$ find testdir -printf '%y %p\n' | tee before.txt
d testdir
d testdir/foo
d testdir/foo/bar
d testdir/foo/bar/baz
f testdir/foo/afile.txt

$ find testdir -depth -type d -empty
testdir/foo/bar/baz

$ find testdir -depth -type d -empty -delete

$ find testdir -printf '%y %p\n' | tee after.txt
d testdir
d testdir/foo
f testdir/foo/afile.txt

$ diff -u {before,after}.txt | tail +4
 d testdir
 d testdir/foo
-d testdir/foo/bar
-d testdir/foo/bar/baz
 f testdir/foo/afile.txt
answered 2010-05-11T13:39:39.690
35

Check whether find <dir> -type f outputs anything. Here's an example:

for dir in A B C; do
    [ -z "`find $dir -type f`" ] && echo "$dir is empty"
done
answered 2010-05-11T13:03:16.207
2

This recursive function would seem to do the trick:

# Bash
findempty() {
    find ${1:-.} -mindepth 1 -maxdepth 1 -type d | while read -r dir
    do
        if [[ -z "$(find "$dir" -mindepth 1 -type f)" ]] >/dev/null
        then
            findempty "$dir"
            echo "$dir"
        fi
    done
}

Given this example directory structure:

    .
    |-- dir1/
    |-- dir2/
    |   `-- dirB/
    |-- dir3/
    |   `-- dirC/
    |       `-- file5
    |-- dir4/
    |   |-- dirD/
    |   `-- file4
    `-- dir5/
        `-- dirE/
            `-- dir_V/

The result of running that function would be:

    ./dir1
    ./dir5/dirE/dir_V
    ./dir5/dirE
    ./dir5
    ./dir2/dirB
    ./dir2

which misses /dir4/dirD. If you move the recursive call findempty "$dir" after the fi, the function will include that directory in its results.

answered 2010-05-11T13:58:48.910
0
find . -name -type d -ls |awk '($2==0){print $11}'
answered 2010-05-11T14:56:10.163

Your Answer