2

This question already has an answer here:

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)

marked as duplicate by Stephen Kitt, roaima, Raphael Ahrens, dhag, Anthon Dec 18 '15 at 16:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7

Using GNU find:

find ~ -type d -empty

(this looks for empty directories starting from your home directory).

1

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

  • 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
  • @EmEsEn, I'm sure your teacher wanted you to think and learn. – Michael Yaeger Dec 22 '16 at 18:18
1

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 directory
    • shopt -s nullglob; shopt -s dotglob in that bash 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 ...
  • wow great! how did you came up with this? – EmEsEn Dec 18 '15 at 14:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.