User Tools

Site Tools


ubuntu:directory:find_and_remove_empty_directories

Ubuntu - Directory - Find and remove empty directories

find -depth -type d -empty -exec rmdir {} \;

This goes down in the directory hierarchy (-depth), finds all the objects that are directories AND are empty (-type d -empty) and executes on them the rmdir command. It works… unless there is some directory with spaces or other weird characters in its name.


A slightly more complicated command for this purpose:

find .  -depth -type d -empty | while read line ; do  echo -n "rmdir '$line" ; echo "'"; done > rmdirs.sh
cat rmdirs.sh
rmdir 'rule/slinky_linux_v0.3.97b-vumbox/images'
rmdir 'rule/slinky_linux_v0.3.97b-vumbox/RedHat/RPMS'
...
source rmdirs.sh

Using the while loop creates a command file (rmdirs.sh) that wraps each directory name in single quotes, so that the rmdir command always receives one single argument. This always works… with the obvious exception of names that contain single quotes!

Dealing with them requires some shell quoting tricks that… todo! For now, you know that whenever you have duplicate files to remove quickly, you can do it by using the two scripts shown here in sequence.

ubuntu/directory/find_and_remove_empty_directories.txt · Last modified: 2020/07/15 09:30 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki