0

This should be fairly simple, but I am not sure what i'm missing.

I'd like to recursively delete empty directories, and get an output for what's being deleted, this command works for sure, but I just can't print the actions of -excec verbosely.

while [ -n "$(find . -depth -type d -empty -exec rm -v -rf {} +)" ]; do :; done

by recursively I mean, I want to keep deleting empty folders, until there's no other empty folder.

$ tree .
.
├── empty
│   └── empty
│       └── empty
└── non-emty
    └── ko

this item will only remove one empty folder in the tree

$ find . -depth -type d -empty -exec rmdir -v {} +
rmdir: removing directory, `./empty/empty'
kmassada
  • 113
  • 5
  • 1
    I worry about the logic of this -- is a directory empty if it only contains directories that are empty? Also -- as far as logging the output -- whenever I do something like this that has the potential to wreck a whole bunch of stuff, I have it output the command it would run but not actually run the command itself. Then, if I actually want to run those commands I can just run the output like a shell script. – chris Apr 14 '13 at 13:09
  • you right, i have the wrong verbiage, it's not quite empty. let me change that. it has nothing to do with logic, lol there's a problem, keep deleting empty directories until there are none left. I try to solve. – kmassada Apr 14 '13 at 13:13

2 Answers2

6

You don't need the while loop and you should use rmdir -p to remove the empty parents

find . -depth -type d -empty -exec rmdir -v -p {} + 
rmdir: removing directory, `./1/3'
rmdir: removing directory, `./1'
rmdir: removing directory, `.'
rmdir: failed to remove directory `.': Invalid argument
rmdir: removing directory, `./2/3'
rmdir: removing directory, `./2'
rmdir: failed to remove directory `./2': Directory not empty

The reason you don't see the output with your command is that you are running it in a subshell $(...) but doing nothing with the returned output you could put an echo before the subsell to print out what it returns

echo $(find . -depth -type d -empty -exec rmdir -v -p {} +)
rmdir: removing directory, `./1/3' rmdir: removing directory, `./1' rmdir: removing directory, `.' rmdir: removing directory, `./2/3' rmdir: removing directory, `./2'
user9517
  • 115,471
  • 20
  • 215
  • 297
0

With find, on both Linux and MacOS, you have the -delete option. It already implies -depth. And for verbose output, you can add -print. So it's just :

find . -type d -empty -delete -print
mivk
  • 4,004
  • 3
  • 37
  • 32