17

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)

chaos
  • 48,171
EmEsEn
  • 181

3 Answers3

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 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 ...
chaos
  • 48,171
  • 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 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
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