Delete Empty Directories on the Command Line with Find
Quickly recursively delete all empty directories. We'll be able to perform a dry run too.
Quick Jump: Demo Video
find is such a useful tool:
# Really recursively delete empty directories. find /path/to/directories -type d -empty -delete # Dry run (print the directories that would have been deleted). find /path/to/directories -type d -empty -print
This came up recently where I was working with a Rails app using Active Storage and after uploading and deleting dozens of test files, Active Storage left behind a bunch of empty directories. I wanted to clean those up, the above did it in about a second.
rm -rf /path/to/directories because there were a number of directories with files that I wanted to keep. For example the directory structure looked like this:
storage ├── 1a │ └── 5n │ └── 1a5n8s46gb8sjnfwv51fwr2gwek6 ├── 1u │ └── a2 │ └── 1ua2l032tv9va6ctdqr1k6gogtjh ├── 26 │ └── nw
There were over a hundred of these directories where most paths such as
26/nw were empty but not all. In this case,
1a5n8s46gb8sjnfwv51fwr2gwek6 is a file.
- 0:24 – Creating a bunch of empty directories to try it out
- 0:54 – Deleting all of the empty directories
- 1:35 – Not deleting directories that have files
- 2:26 – Performing a dry run with print instead of delete
- 3:26 – Real world use case
When was the last time you had to delete a bunch of empty directories?