How do I remove all empty directories using bash

hi guys,

I have multiple empty directories. I would like to traverse entire directory structure and remove automatically all directories. Is there an easy way to do this rather then going one by one? The command should be recursive and remove all subdirectories as well.

thank you

Hi Caroline,

Please used following bash command to accomplish required task

find /var/www/ -type d -empty -print0 -exec rmdir {} ;

i assume your have empty directories in /var/www tree

if you want to remove empty directories in current directory you can use find -type d -empty -print0 -exec rmdir {} ;

Let me get into little more details

ok if you want to search for empty directory in /var/www tree you can use

find /var/www/ -type d -empty -print0

if you want to delete then silently with out any prompt use -exec

find /var/www/ -type d -empty -print0 -exec rmdir {} ;

if you want to delete then and see a prompt so you can skip some off you should use use -ok rather than using -exec

find /var/www/ -type d -empty -print0 -ok rmdir {} ;

Thanks

bnhashmi

Hi Caroline,

Please used following bash command to accomplish required task

find /var/www/ -type d -empty -print0 -exec rmdir {} ;

i assume your have empty directories in /var/www tree

if you want to remove empty directories in current directory you can use find -type d -empty -print0 -exec rmdir {} ;

Let me get into little more details

ok if you want to search for empty directory in /var/www tree you can use

find /var/www/ -type d -empty -print0

if you want to delete then silently with out any prompt use -exec

find /var/www/ -type d -empty -print0 -exec rmdir {} ;

if you want to delete then and see a prompt so you can skip some off you should use use -ok rather than useing -exec

find /var/www/ -type d -empty -print0 -ok rmdir {} ;

Thanks

bnhashmi

Yes, you can use the rm command with the -r (recursive) and -f (force) options to remove directories and their contents recursively. Here’s the command you can use:
rm -rf

Replace with the path to the top-level directory you want to remove. This command will remove the specified directory and all its subdirectories, as well as any files or directories within them, without prompting for confirmation.

Please exercise caution when using the rm command with the -r and -f options, as it can permanently delete data without any confirmation. Double-check your command and ensure you specify the correct directory path to avoid unintentional data loss.

Another simple way to remove only empty directories:

$ find /path/to/start -type d -empty -delete

Be careful when using this command, as it will delete all the empty directories it finds! You may want to run the command without -delete first to make sure it’s finding only the directories you want to delete: