Say I have a directory named foo/
. This folder includes subdirectories. How can I delete all the empty directories in one command?
Say I have a directory named foo/
. This folder includes subdirectories. How can I delete all the empty directories in one command?
Try this command:
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 cased
stands for the file type directory.The
-delete
option is the action to perform, and holds true for all files found in the search.You can take advantage of the
rmdir
command's refusal to delete non-empty directories, and thefind -depth
option to traverse the directory tree bottom-up:(and ignore the errors), or append
2>/dev/null
to really ignore them.The
-depth
option tofind
starts finding at the bottom of the directory tree.rm -rf
will delete all the files in the directory (and its subdirectories, and ....) AND all the directories and everything.Will delete all empty directories. It'll throw up an error for every non-empty directory and file, to stop those errors from cluttering your terminal, use
For if you only want to delete the direct subdirectories of
foo/
.Python approach
This works like so:
os.walk()
function to walk recursively the directory tree. On each iterationr
is set to current folder that we're accessing,s
contains list of directories withinr
, andf
will contain list of files in that folder. Of course iff
ands
are empty, we know thatr
is empty.empty
, the list of all directories that are empty, based on the evaluation stated above.map()
is used to performos.rmdir()
on each item inempty
list. List comprehension could be used as well as alternative.As a script this would be as so: