I want to delete empty directories without using find command find . -empty -type d -delete. like the following:

if [ "$(ls -d *)" ]; then
   echo "Not Empty"
   echo "Delete"

How do I delete empty directories only using ls?

| improve this question | | | | |
  • (assuming bash) If you want to traverse an entire directory without find and do something with those files, you should either use globstar (bash 4+) or recursion. And since I don't think you can make globstar run in DFS order, you would pretty much be limited to recursion. – user60101 Sep 14 '14 at 22:33
  • 8
    Why it has to be without find? – Braiam Sep 14 '14 at 22:51
  • Here are several methods that you could use: stackoverflow.com/questions/2154166/…. You'd need to modify the body of these loops to do the actual deletions. – slm Sep 15 '14 at 1:21

rmdir will delete empty folders (while leaving other folders alone), so you can use something like:

rmdir */

Or, if you're using bash 4+ and you want recursiveness (other shells have other names for the same thing):

shopt -s globstar
rmdir **/

This will give you a lot of error messages, however (one for every non-empty folder).

| improve this answer | | | | |
  • Thanks! Then how would I list the empty directories with ls? – EPSILONsdfsdfdsf Sep 15 '14 at 2:02
  • And how would I delete recursively> – EPSILONsdfsdfdsf Sep 15 '14 at 2:05
  • 1
    +1, but still a couple of problems with globstar. It doesn't traverse dfs, so if you /foo/foo1/foo2, and none of the dirs contain anything else, it will delete foo2, but fail for the others. rmdir **/ is also rather likely to hit ARG_MAX and fail for a tree of reasonable size. Also may want to turn dotglob on if you want hidden directories. – user60101 Sep 15 '14 at 3:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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