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)


Using GNU find:

find ~ -type d -empty

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

|improve this answer|||||

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 ...
|improve this answer|||||
  • wow great! how did you came up with this? – EmEsEn Dec 18 '15 at 14:23
  • This is a bit of a Rube Goldberg machine. Aside from not having any issue with OS’s that use link count of mount points for private purposes (a rather arcane use case), this incantation has no benefit I can see over the linked duplicate answer (which, to be fair, I wrote) using -links 2 at 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 1 '19 at 19:32

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

|improve this answer|||||
  • 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

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