I want to show all the empty directories under my home directory, using shell script, can you help me find the code? (without using find
's -empty
)
Asked
Active
Viewed 2.0k times
17
3 Answers
33
Using GNU find
:
find ~ -type d -empty
(this looks for empty directories starting from your home directory).

Stephen Kitt
- 434,908
4
If your find has no -empty
flag (like for exmaple the one from busbox
or any other POSIX-conformant find
), you have to do it that way (inspired by @jordanm's answer), using bash
:
find . -type d -exec bash -c 'shopt -s nullglob; shopt -s dotglob;
a=("$1"/*); [[ ${a[@]} ]] || printf "%s\n" "$1"' sh {} \;
-type d
find only directories-exec bash -c '...' sh {} \;
calls a bash shell for every found directoryshopt -s nullglob; shopt -s dotglob
in thatbash
instance,nullglob
prevents bash from returning the pattern when matching nothing.dotglob
includes files and directories beginning with a dot (.
).a=("$1"/*)
fill the array$a
with all items in processing directory[[ ${a[@]} ]]
check if$a
contains items. If not...printf "%s\n" "$1"
prints the directory name
If you want to process that list further, make sure to delimit the items by nullbyte:
find . -type d -exec bash -c 'shopt -s nullglob; shopt -s dotglob;
a=("$1"/*); [[ ${a[@]} ]] || printf "%s\0" "$1"' sh {} \; | xargs -0 ...
3
If you want to find empty directories that are in your home directory, except of all empty directories under home tree, you can use GNU find
:
find ~ -maxdepth 1 -type d -empty

MatthewRock
- 6,986
-
I am sorry, I forgot to mention that our teatcher want us to do so without using -empty (that's the hard part) – EmEsEn Dec 18 '15 at 13:20
-
4
-links 2
at https://unix.stackexchange.com/a/248986/147196 — and, if set loose on a large directory tree, it will be much less performant than the-links
answer. – Trey Aug 01 '19 at 19:32