I want to count empty and non empty directories. But all the empty directories and directories that contains files and subdirectories have same size 4096. So empty directories also count in non empty directories because of 4096 size. And count of empty directories obtains zero.
-
3Note: "to count non empty and empty directories with size 4096" (the title) and "to count empty and non empty directories" (the first sentence of the body) are two different tasks. In ext a directory can take more bytes regardless whether it's empty or not. It's not clear which task you want. Please [edit] and clarify. – Kamil Maciorowski Aug 29 '21 at 07:13
-
the 4096 size is the size of the inodes needed to contains the list of files+dirs within that directory. It will be 1 block of inodes (4k) if the dir was always empty or always had few files+dirs within, or more if you have many files+dirs within that directory. Once it is enlarged to hold a long list of filenames, it will not shrink back after you delete those files. You would need to create another dir and replace it with that new one. – Olivier Dulac Aug 30 '21 at 07:05
2 Answers
If all you care about is emptiness, find
seems like the most straightforward tool for the job.
find . -type d -empty
will list all empty folders in the current directory. Change the dot to search elsewhere.
find . -maxdepth 1 -type d -empty
will avoid looking at subdirectories.
The end goal was to count them, so based on @alecxs comment :
find . -maxdepth 1 -type d -empty -printf '\n' | wc -l
.
This has the advantage of not forking a process for every directory so should be faster, especially if the number of empty directories is large.

- 229
-
it will recursively look for empty directories. E.g. it'll find
./foo/bar/
too, if it's empty – ilkkachu Aug 29 '21 at 09:11 -
I normally put an alias to my bash for folder size into (/root/).bashrc
alias ds='du --max-depth=1 -ch'
So I don't type whole thing every time. This will list folder sizes in human readable format ie (4K, 1M, 2G)
so then you can just issue this command and pipe through grep like following:
ds |grep -c 4.0K
this will count empty directories or:
ds |grep -cv 4.0K
will count non-empty directories
if you don't want to use alias, just replace ds
with du --max-depth=1 -ch
If you want to be absolutely precise you can skip h
and just do:
du --max-depth=1 -cb |grep -c "^4096"$'\t'
Please note that directory size of 4096B will also be shown if directory has symbolic links inside or files with size of 0B, so this will NOT correctly display empty directory count, thus probably better to use above solution with find
Another useful thing that I normally use is to list large directories (larger than 1G and sort them)
ds |grep "G"$'\t' |sort -n
This should help.

- 76
- 6