Linux delete all empty folders

How do I delete all empty directories in a directory from the command line?

Say I have a directory named foo/ . This folder includes subdirectories. How can I delete all the empty directories in one command?

5 Answers 5

find . -empty -type d -delete 

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 case d stands for the file type directory.

The -delete option is the action to perform, and holds true for all files found in the search.

Hey Bill, I tried to post another similiar question and it wouldn’t let me because it said it was a dupe, so I was hoping you might be able to answer me here. Say I wanted to do the same thing as above but remove all directories whether they are empty or not.

The way you would remove directories, regardless of whether or not they are empty, type the following command: rm -rf . This will remove the directory, along with all its contents including files and subdirectories. The -r option means delete recursively, while the -f command means don’t prompt before deleting. If you want to be prompted before deleting a directory/file, however, replace the -f option with the -i option.

It is possible to do this by using a pipe to feed the stdout of one command (e.g. find ) into the stdin of the other (e.g. rm ), however, be very careful since it may wipe out or delete files/directories that you don’t want to delete! For further information on how to do this, see the man pages for each of these commands. To be safe, always test such things in a temporary directory before trying out on the real thing.

@joeybaruch On MacOS almost every directory you «visited» with Finder.app contains a .DS_Store hidden file, that usually stores your sorting/viewing preferences for that directory. Other apps may add other hidden files (e.g. Adobe Bridge may add a .BridgeLabelsAndRatings file), so perhaps those directories aren’t really empty. Anyways, you can remove the .DS_Store file with find . -name ‘.DS_Store’ -delete and then try again to remove the empty directories with the suggested command.

Источник

Delete empty files and directories in Linux

We’ll learn how to remove empty directories and empty file on Linux.

Читайте также:  Hp pavilion gaming 15 linux

Empty directories don’t take up any disk space, but they’re good to keep them tidy. We should clear out old files and folders periodically.

All the instructions in this tutorial are for Linux systems. They won’t work on Windows.

Delete Empty Files in a Directory

You can use the `find` command to remove all the empty files in an existing folder.

$ find . -type f -empty -print -delete

To delete empty directories, we first need to search for all the empty folders in the specified folder and then, delete them.

To find all the empty directories in the current directory, use the following command: find. −type d −empty −print | xargs rm −rf. Add the −delete option to remove them.

Let’s take an example to better explain this concept.

A directory containing both empty and non-empties may be considered. Here, the file prefixed with data-filename is a non-empty file and the one prefixed with empty is an empty file.

|-- data-file1 |-- data-file2 |-- empty-file1 |-- empty-file2 |-- empty-file3 |-- empty file 4 |-- mydir1 | |-- data-file3 | `-- empty-file5 |-- mydir2 | |-- data-file4 | `-- empty-file6 `-- mydir3 `-- mydir4 `-- mydir5

We’ll now run the above command inside these directories. It will delete all empty files recursively — meaning that the empty-file4 and empty-file5 inside the directories mydir1 and mydird2, respectively, will be removed too.

$ find . -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir1/empty-file5 ./mydir2/empty-file6 ./empty file 4

Let’s look at the output carefully. We’ll see that this operation has removed the files whose names include spaces from the directory.

It has deleted only empty files and not the directories like mydir1, mydir2, mydir4, and mydir6.

Non-Recursive Deletion of Empty Files

We’ve talked about deleting empty files from directories recursively so far. But what if we want to remove empty files from the current directory itself?

The find utility has an option −maxDepth that defines the maximum depth at which the find utility searches for files.

Using −maxdepth1, the ‘f’ (file) command will search for files in the current directory only.

$ find . -maxdepth 1 -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./empty file 4

Delete All Empty Directories

We can search for files by using -type f with the find command −

$ find . -type d -empty -print -delete

It will remove all the empty directories from the current directory.

Let’s run this command inside the directory where we saved our script.

$ find . -type d -empty -print -delete ./mydir3 ./mydir4/mydir5 ./mydir4

After deleting the mydir5 folder, mydir3 is no longer an empty directory; instead, it contains the files from mydir2.

Non-Recursive Deletion of Empty Directories

By using −maxdepth 1, the find utility searches only for empty directories in the current working directory.

$ find . -maxdepth 1 -type d -empty -print -delete ./mydir3

Delete Empty Files and Directories Together

It’s now finally the right moment to combine everything that we’ve learned so far. Delete all the empty files and folders from the current directory by running one command.

Читайте также:  Даниэл дж баррет linux основные команды

We’ll use the logical OR (OR) operation (-o), with the find utility, to search for empty files or directories.

$ find . -type d -empty -print -delete -o -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir1/empty-file5 ./mydir2/empty-file6 ./mydir3 ./mydir4/mydir5 ./mydir4

The −o option splits the command from the filename into two parts. The fist part, −type d −empty − print −delete, deletes all the empty directories, whereas the second part, − type f −empty − print − delete, deletes all the files which are empty.

We can use −maxdepth 0 to delete the empty files/directoires recursively.

$ find . -maxdepth 1 -type d -empty -print -delete -o -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir3

Conclusion

Here, we’ve learnt about empty files, empty folders, and how to remove them in Linux. We’ve looked at two different ways of deleting files − Recursive and Non−Recursive.

It is important to review all the directories and delete any unnecessary ones before removing them. In all the examples discussed above, we can use the −recurse option to review all the directories that would be removed.

As a best practice, we can set up a cron task to remove empty folders and subfolders from our system. This way, we won’t ever accumulate empty folders and subfoldes on our computer.

Источник

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

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

Откройте терминал (командную строку) и перейдите командой 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 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.

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!

Источник

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