Linux remove all empty directories

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.

Читайте также:  Linux socks to http proxy

@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 to Find and Delete Empty Directories in Linux

Many times empty directories get cluttered in the Linux file system, and it becomes a difficult task to manually search for and delete each of them. The command rmdir (remove directory) is used in Linux to delete empty folders.

Читайте также:  Kali linux usb image

The command is quite simple to use and the basic syntax is:

Here, ‘empty folder name1‘, ‘empty folder name2‘, etc. are the names of the folders including the full path. If the folders are in the same directory then, as you might already know, there is no need to write down full paths.

You can also use wildcard expressions to remove empty directories with patterns in their names. For example, to remove empty directories with the substring ‘test‘ in their name, run:

Remove Empty Directories

However, to use rmdir we always need to specify the name (or full path) of each empty directory to be removed. There is no option in rmdir to recursively look for empty directories and then remove them.

We make use of the functionalities of the find command in such cases.

Find and Remove Empty Directories in Linux

The find command is used to search for files and folders in Linux based on different parameters like filename, size, type, etc. We will use find to determine empty directories recursively and then execute rmdir to delete the found directories.

Use the argument ‘-empty’ to look for empty objects and specify ‘-type d’ to only find directories.

$ find path_of_folder_to_search -type d -empty

To find empty directories recursively in the same folder, run:

Find Empty Directories

Now, since we already have the recursively found list of empty directories, we use the ‘-exec’ argument of the find command to run rmdir over them.

$ find . -type d -empty -exec rmdir <> \;

The placeholder <> substitutes each entry in the list of found directories and ‘\;’ signifies the end of the command to be executed.

However, even with this, it will just do a single round of search and remove directories that are empty, but it will not remove directories that become empty after the first round of deletion.

To tackle this, we simply use the ‘-delete’ option, which will repeatedly delete all empty directories till the top-level directory.

$ find . -type d -empty -delete

Find and Delete Empty Directories

This is how we can remove all empty directories recursively in Linux.

Conclusion

We learned how to use the rmdir command and find command in Linux to delete empty directories recursively. Learn more about these commands in their respective man pages:

Thanks for reading and do share your thoughts below!

Источник

Удаляем пустые файлы и директории

Рассмотрим, как удалить все пустые файлы или директории в определенной директории. Сделать это очень просто через командную строку, используя команды find, rm и rmdir.

Читайте также:  Linux посмотреть скорость сети

Откройте терминал (командную строку) и перейдите командой cd в ту директорию, в которой вам необходимо удалить пустые файлы:

Удаляем пустые файлы

Выведем список пустых файлов. Для этого выполним команду find и укажем ей, что нам в текущей директории необходимо найти только файлы (параметр -type f) и эти файлы должны быть пустыми (параметр -empty):

Теперь воспользуемся аргументом -exec, который позволяет выполнить определенную команду над списком файлов. Мы укажем, что хотим выполнить команду rm (удалить файл). Итак, чтобы удалить пустые файлы выполните команду:

find . -type f -empty -exec rm <> \;

Удаляем пустые директории

Сначала просто посмотрим, какие директории у нас не содержат файлов. Для этого, так же как и для файлов используем команду find с ключом -empty, но указываем -type d. Выполним в командной строке:

Получим список пустых директорий.

Теперь нам нужно их удалить. Аргументу -exec укажем команду rmdir (удалить директори). Чтобы удалить пустые директории выполняем:

find . -type d -empty -exec rmdir <> \;

Обращаю ваше внимание на то, что выполнять данные команды нужно с осторожностью, чтобы случайно не удалить то, что не нужно. Также нельзя выполнять их в системных директориях, так как в большинстве случаев пустые файлы и директории созданы там специально, и их отсутствие приведет к сбоям в системе.

Дополнительную информацию по команде find вы можете почитать в статье Команда find: широкие возможности для поиска файлов в Linux.

Источник

How can I recursively delete all empty files and directories in Linux?

How can I recursively cleanup all empty files and directories in a parent directory? Let’s say I have this directory structure:

Parent/ |____Child1/ |______ file11.txt (empty) |______ Dir1/ (empty) |____Child2/ |_______ file21.txt |_______ file22.txt (empty) |____ file1.txt 
Parent/ |____Child2/ |_______ file21.txt |____ file1.txt 

I wasn’t confused, per se, but, even before I saw the comments, I thought it was confusing that the illustration had multiple files with the same name. You might want to consider using a naming convention like Child1/file11.txt , Child2/file21.txt and Child2/file22.txt .

3 Answers 3

This is a really simple one liner:

It’s fairly self explanatory. Although when I checked I was surprised that it successfully deletes Parent/Child1. Usually you would expect it to process the parent before the child unless you specify -depth .

This works because -delete implies -depth . See the GNU find manual:

-delete Delete files; true if removal succeeded. If the removal failed, an error message is issued. If -delete fails, find’s exit status will be nonzero (when it eventually exits). Use of -delete automatically turns on the -depth option.

Note these features are not part of the Posix Standard, but most likely will be there under many Linux Distribution. You may have a specific problem with smaller ones such as Alpine Linux as they are based on Busybox which doesn’t support -empty .

Other systems that do include non-standard -empty and -delete include BSD and OSX but apparently not AIX.

Источник

Оцените статью
Adblock
detector