- How to remove all empty directories in a subtree?
- 8 Answers 8
- How do I delete all empty directories in a directory from the command line?
- 5 Answers 5
- Find Empty Directories in Linux Command Line
- Find Empty Directories in Linux
- Find Empty Files in Linux
- Delete Empty Files and Directories using Find Command
- Delete Empty Files and Directories using xargs and find-exec
- Final Words
How to remove all empty directories in a subtree?
but I needs to be run multiple times in order to remove directories containing empty directories only. Moreover, it’s quite slow, especially under cygwin.
8 Answers 8
Combining GNU find options and predicates, this command should do the job:
find . -type d -empty -delete
- -type d restricts to directories
- -empty restricts to empty ones
- -delete removes each directory
The tree is walked from the leaves without the need to specify -depth as it is implied by -delete .
I would add -mindepth 1 here, to prevent from deleting the starting directory itself, if it would be empty.
! has a special meaning for the shell. You need to escape it. Something like: \! -name ‘Completed’ just before -delete should work. Or you just put a marker file in this directory.
List the directories deeply-nested-first.
find . -depth -type d -exec rmdir <> \; 2>/dev/null
(Note that the redirection applies to the find command as a whole, not just to rmdir . Redirecting only for rmdir would cause a significant slowdown as you’d need to invoke an intermediate shell.)
You can avoid running rmdir on non-empty directories by passing the -empty predicate to find. GNU find tests the directory when it’s about to run the command, so directories that have just been emptied will be picked up.
find . -depth -type d -empty -exec rmdir <> \;
Another way to speed up would be to group the rmdir invocations. Both are likely to be noticeably faster than the original, especially under Cygwin. I don’t expect much difference between these two.
find . -depth -type d -print0 | xargs -0 rmdir 2>/dev/null find . -depth -type d -exec rmdir <> + 2>/dev/null
Which method is faster depends on how many non-empty directories you have. You can’t combine -empty with methods for grouping invocations, because then the directories that only contain empty directories aren’t empty by the time find looks at them.
Another method would be to run multiple passes. Whether this is faster depends on a lot of things, including whether the whole directory hierarchy can remain in the disk cache between find runs.
while [ -n "$(find . -depth -type d -empty -print -exec rmdir <> +)" ]; do :; done
Alternatively, use zsh. The glob qualifier F matches non-empty directories, so /^F matches empty directories. Directories that only contain empty directories can’t be matched so easily.
(This terminates when rmdir receives an empty command line.)
@maaartinus: I’m curious: do you have a similar data set where you could try without -p ? I wouldn’t have thought it would make a difference.
@maartinus — other little optimizations: adding -empty should work with this one (although I’m not sure exactly how much it’ll gain). And very, very trivially, since you probably don’t want to remove . , use -mindepth 1 .
It was not the removal but the process start up overhead, what took nearly all the time. I had overlooked the -depth argument, which makes rmdir -p useless. I’ve changed my comment already. The 90 s was my original attempt; there’s nothing surprising here.
I realized we can remove the rmdir command call altogether, at least with GNU find, with this command: find . -depth -type d -empty -delete
find . -depth -type d -exec rmdir <> +
is the simplest and standard compliant answer to this question.
The other answers given here unfortunately all depend on vendor specific enhancements that do not exist on all systems.
This answer raises an error for each directory that cannot be deleted which may be less than desirable.
It will also fail if you deal with a huge amount of directories, as there is a limit on how many characters rmdir can accept. Using \; instead of + will fix this issue, but it will make the command significantly slower.
Also all these solutions will fail with hidden files, like .DS_Store on Mac or Desktop.ini on Windows.
If you just tack a -p on your rmdir , that’ll work in one pass. It won’t be pretty or optimal, but it should get everything. That tells rmdir to remove any non-empty parent directories of the one you’re removing.
You can save a little bit by adding the -empty test to find, so it doesn’t bother with non-empty directories.
I use these aliases for frequently used find commands, especially when I cleaning up disk space using dupeguru, where removing duplicates can result in a lot of empty directories.
Comments inside .bashrc so I won’t forget them later when I need to tweak it.
# find empty directories alias find-empty='find . -type d -empty' # fine empty/zero sized files alias find-zero='find . -type f -empty' # delete all empty directories! alias find-empty-delete='find-empty -delete' # delete empty directories when `-delete` option is not available. # output null character (instead of newline) as separator. used together # with `xargs -0`, will handle filenames with spaces and special chars. alias find-empty-delete2='find-empty -print0 | xargs -0 rmdir -p' # alternative version using `-exec` with `+`, similar to xargs. # <>: path of current file # +: <> is replaced with as many pathnames as possible for each invocation. alias find-empty-delete3='find-empty -exec rmdir -p <> +' # for removing zero sized files, we can't de-dupe them automatically # since they are technically all the same, so they are typically left # beind. this removes them if needed. alias find-zero-delete='find-zero -delete' alias find-zero-delete2='find-zero -print0 | xargs -0 rm' alias find-zero-delete3='find-zero -exec rm <> +'
How do I delete all empty directories in a directory from the command line?
Say I have a directory named foo/ . This folder includes subdirectories. How can I delete all the empty directories in one command?
5 Answers 5
find . -empty -type d -delete
The find command is used to search for files/directories matching a particular search criteria from the specified path, in this case the current directory (hence the . ).
The -empty option holds true for any file and directory that is empty.
The -type d option holds true for the file type specified; in this case d stands for the file type directory.
The -delete option is the action to perform, and holds true for all files found in the search.
Hey Bill, I tried to post another similiar question and it wouldn’t let me because it said it was a dupe, so I was hoping you might be able to answer me here. Say I wanted to do the same thing as above but remove all directories whether they are empty or not.
The way you would remove directories, regardless of whether or not they are empty, type the following command: rm -rf
It is possible to do this by using a pipe to feed the stdout of one command (e.g. find ) into the stdin of the other (e.g. rm ), however, be very careful since it may wipe out or delete files/directories that you don’t want to delete! For further information on how to do this, see the man pages for each of these commands. To be safe, always test such things in a temporary directory before trying out on the real thing.
@joeybaruch On MacOS almost every directory you «visited» with Finder.app contains a .DS_Store hidden file, that usually stores your sorting/viewing preferences for that directory. Other apps may add other hidden files (e.g. Adobe Bridge may add a .BridgeLabelsAndRatings file), so perhaps those directories aren’t really empty. Anyways, you can remove the .DS_Store file with find . -name ‘.DS_Store’ -delete and then try again to remove the empty directories with the suggested command.
Find Empty Directories in Linux Command Line
Here are a few examples of finding and deleting empty directories in the Linux command line.
Linux users are bound to have multiple empty directories and it’s quite easy to find them.
But wait, just listing empty directories won’t do the job so I’ll also show you how to delete them!
Find Empty Directories in Linux
To Find an empty directory, you’ll just have to pair the -empty option with the find command. Let me show you how:
find /home/sagar/Files -type d -empty
When you use the find command with the -type d option, it will search for directories only.
Find Empty Files in Linux
As I mentioned just above that -type d was used to search for directories, you can change this behavior to search for files by using type f .
find /home/sagar/Files -type f -empty
Find is an excellent command. If you are interested in learning more, here are a few more examples 👇
Delete Empty Files and Directories using Find Command
To delete the files and directories given by the find command, you just have to use the -delete option.
So let’s start with deleting empty directories:
find /home/sagar/Files -empty -type d -delete
You can do the same with files by interchanging -type d with -type f :
find /home/sagar/Files -empty -type f -delete
Delete Empty Files and Directories using xargs and find-exec
The find exec is nothing but allows you to execute custom operations such as running scripts and executing programs on search results.
While xargs can take input from the standard input or even consider the output of another command as input and can use it as a command.
So let’s start with removing empty files and directories using the find with the exec command.
To remove empty files, you just have to utilize the given command:
find /home/sagar/Files -type f -empty -print0 -exec rm -v "<>" \;
And if you want to remove directories, the given command should work just fine:
find /home/sagar/Files -type d -empty -print0 -exec rmdir -v "<>" \;
Now, let’s use xargs with find to remove empty directories:
find /home/sagar/Files -type d -empty -print0 | xargs -0 -I <> /bin/rmdir "<>"
Similarly, with a few tweaks to the above command and you can remove empty files:
find /home/sagar/Files -type f -empty -print0 | xargs -0 -I <> /bin/rm "<>"
And if you’re curious to learn more about xargs, we already have a detailed guide on that topic:
Final Words
Well, this was a short guide on how you can remove empty files and folders and I’ve tried my best to make it beginner friendly.
But still, if you encounter any doubts, I’d be happy to help!