- How to find and delete directory recursively on Linux or Unix-like system
- Find command syntax to delete directory recursively
- Finding and deleting directory recursively using xargs
- Shell script to recursively remove backups older than 30 days
- Linux / Unix: Find and Delete All Empty Directories & Files
- Method # 1: Find and delete everything with find command only
- Delete empty directories
- Delete empty files
- How to count all empty files or directories?
- Method # 2: Find and delete everything using xargs and rm/rmdir command
- Как удалить каталог в Linux
- How to Remove (Delete) Directory in Linux
- В этой статье мы расскажем , как удалить каталоги в Linux , используя mdir, rm и find команду.
- Прежде чем вы начнете
- Удаление каталогов с rmdir
- Удаление каталогов с rm
- Удаление каталогов с find
- Удаление всех пустых каталогов
- / bin / rm: список аргументов слишком длинный
- Вывод
- Find and Delete Empty Directories on the Linux Command Line
- Finding Empty Directories
- Finding Empty Files (zero-byte size)
- Deleting Empty Files and Directories
- Using the find Command Delete Option
- Using the find Command Execute Option
- Using xargs to Delete Arguments in Data Stream
- Conclusion
How to find and delete directory recursively on Linux or Unix-like system
Find command syntax to delete directory recursively
Try the find command:
find /dir/to/search/ -type d -name «dirName» -exec rm -rf <> +
Another option is as follows to recursively remove folders on Linux or Unix:
find /dir/to/search/ -type d -name «dirName» -exec rm -rf \;
Warning : Be careful with the rm command when using with find. You may end up deleting unwanted data.
Find will execute given command when it finds files or dirs. For example:
find . -type d -name «foo» -exec rm -rf <> +
OR
find . -type d -name «bar» -exec rm -rf «<>» \;
Sample outputs:
You can find directories that are at least four levels deep in the working directory /backups/:
find /backups/ -type d -name «bar» -depth +4 -print0 -exec rm -rf <> +
Finding and deleting directory recursively using xargs
The syntax is as follows to find and delete directories on Linux/Unix system. For example, delete all empty directories:
find /path/to/dir/ -type d -empty -print0 | xargs -0 -I <> /bin/rm -rf «<>»
In this example, remove all foo directories including sub-diretories in /backups/ folder:
find /backups/ -type d -name «foo*» -print0 | xargs -0 -I <> /bin/rm -rf «<>»
The second command is a secure version. It is fast too, and it deals with weird directory names with white spaces and special characters in it:
Hence, I would like readers to use the following syntax:
find /path/to/search/ -name «pattern» -print0 | xargs -0 -I <> /bin/rm -rf «<>»
Where find command options are:
- -name «pattern» : Base of file name that matches shell pattern pattern. For example, foo, Foo*3 and so on.
- -print0 : Show the full file name on the standard output, followed by a null character. This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs
And xargs command options are:
- -0 : Input items given by find are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
- -I <> : <> in the initial-arguments with names read from standard input. For example, dir names given by find command./li>
- /bin/rm -rf «<>« : Run rm command that remove files or directories passed by <> .
Shell script to recursively remove backups older than 30 days
Here is my sample script that removes older weekly backup of my VM tarballs stored in the following format:
Источник
Linux / Unix: Find and Delete All Empty Directories & Files
H ow do I find out all empty files and directories on a Linux / Apple OS X / BSD / Unix-like operating systems and delete them in a single pass?
You need to use the combination of find and rm command. [donotprint]
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | find command |
Est. reading time | 5m |
[/donotprint]GNU/find has an option to delete files with -delete option. Please note that Unix / Linux filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by many utilities including rm command. To avoid problems you need to pass the -print0 option to find command and pass the -0 option to xargs command, which prevents such problems.
Method # 1: Find and delete everything with find command only
The syntax is as follows to find and delete all empty directories using BSD or GNU find command:
Find and delete all empty files:
Delete empty directories
In this example, delete empty directories from
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Delete empty files
In this example, delete empty files from
Fig.01: Delete empty directories and files.
How to count all empty files or directories?
The syntax is as follows:
- -empty : Only find empty files and make sure it is a regular file or a directory.
- -type d : Only match directories.
- -type f : Only match files.
- -delete : Delete files. Always put -delete option at the end of find command as find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the starting points you specified.
This is useful when you need to clean up empty directories and files in a single command.
Method # 2: Find and delete everything using xargs and rm/rmdir command
The syntax is as follows to find and delete all empty directories using xargs command:
Источник
Как удалить каталог в Linux
How to Remove (Delete) Directory in Linux
В этой статье мы расскажем , как удалить каталоги в Linux , используя mdir, rm и find команду.
Существует несколько различных способов удаления каталогов в системах Linux. Если вы используете файловый менеджер Desktop, такой как «Файлы Gnome» или «Dolphin» в KDE, вы можете удалять файлы и каталоги с помощью графического пользовательского интерфейса менеджера. Но если вы работаете на автономном сервере или хотите удалить несколько каталогов одновременно, лучшим вариантом будет удаление каталогов (папок) из командной строки.
Прежде чем вы начнете
При удалении каталога с помощью файлового менеджера на рабочем столе этот каталог фактически перемещается в корзину и может быть легко восстановлен.
Будьте особенно осторожны при удалении файлов или каталогов из командной строки, поскольку после удаления каталога с помощью команд, описанных в этой статье, его невозможно полностью восстановить.
В большинстве файловых систем Linux удаление каталога требует разрешения на запись в каталог и его содержимое. В противном случае вы получите ошибку «Операция не разрешена».
Имена каталогов с пробелом в них должны быть экранированы обратной косой чертой ( / ).
Удаление каталогов с rmdir
Чтобы удалить каталог с помощью rmdir , введите команду, а затем имя каталога, который вы хотите удалить. Например, чтобы удалить каталог с именем dir1 , введите:
Если каталог не пустой, вы получите следующую ошибку:
В этом случае вам нужно будет использовать rm команду или вручную удалить содержимое каталога, прежде чем вы сможете удалить его.
Удаление каталогов с rm
rm утилита командной строки для удаления файлов и каталогов В отличие rmdir от rm команды можно удалять как пустые, так и непустые каталоги.
По умолчанию при использовании без какой-либо опции rm не удаляются каталоги. Чтобы удалить пустой каталог, используйте опцию -d ( —dir ) и удалите непустой каталог, а все его содержимое используйте опцию -r ( —recursive или -R ).
Например, чтобы удалить каталог dir1 со всем его содержимым, вы должны набрать:
Если каталог или файл в каталоге защищен от записи, вам будет предложено подтвердить удаление. Чтобы удалить каталог без запроса, используйте -f параметр:
Чтобы удалить несколько каталогов одновременно, вызовите rm команду, а затем имена каталогов, разделенные пробелом. Команда ниже удалит все перечисленные каталоги и их содержимое:
-i Параметр указывает rm на запрос на подтверждение удаления каждого подкаталога и файла. Если каталог содержит много файлов, это может немного раздражать, поэтому вы можете рассмотреть возможность использования -I опции, которая предложит вам только один раз, прежде чем продолжить удаление.
Вы также можете использовать обычные расширения для сопоставления и удаления нескольких каталогов. Например, чтобы удалить все каталоги первого уровня в текущем каталоге, который заканчивается на _bak , вы должны использовать следующую команду:
Использование регулярных расширений при удалении каталогов может быть рискованным. Рекомендуется сначала перечислить каталоги с помощью ls команды, чтобы вы могли видеть, какие каталоги будут удалены перед выполнением rm команды.
Удаление каталогов с find
find утилита командной строки, которая позволяет вам искать файлы и каталоги на основе заданного выражения и выполнять действия с каждым соответствующим файлом или каталогом.
Наиболее распространенный сценарий — использовать find команду для удаления каталогов на основе шаблона. Например, чтобы удалить все каталоги, которые заканчиваются _cache в текущем рабочем каталоге, вы должны выполнить:
Давайте проанализируем команду выше:
- /dir — рекурсивный поиск в текущем рабочем каталоге ( . ).
- -type d — ограничивает поиск по каталогам.
- -name ‘*_cache’ — искать только каталоги, которые заканчиваются _cache
- -exec — выполняет внешнюю команду с необязательными аргументами, в данном случае, то есть rm -r .
- <> + — добавляет найденные файлы в конец rm команды.
Удаление всех пустых каталогов
Чтобы удалить все пустые каталоги в дереве каталогов, вы должны выполнить:
Вот объяснение используемых опций:
- /dir — рекурсивный поиск по /dir каталогу.
- -type d — ограничивает поиск по каталогам.
- -empty — ограничивает поиск только пустыми каталогами.
- -delete — удаляет все найденные пустые каталоги в поддереве. -delete можно удалить только пустые каталоги.
Используйте -delete опцию с особой осторожностью. Командная строка find оценивается как выражение, и если вы -delete сначала добавите параметр, команда удалит все, что находится ниже указанных вами начальных точек.
Всегда проверяйте команду сначала без -delete опции и используйте -delete в качестве последней опции.
/ bin / rm: список аргументов слишком длинный
Это сообщение об ошибке появляется при использовании rm команды для удаления каталога, содержащего огромное количество файлов. Это происходит потому, что количество файлов превышает системное ограничение на размер аргумента командной строки.
Есть несколько разных решений этой проблемы. Например, вы можете cd в каталог и вручную или с помощью цикла удалить подкаталоги один за другим.
Самое простое решение — сначала удалить все файлы в каталоге с помощью find команды, а затем удалить каталог:
Вывод
С помощью rm и find вы можете удалять каталоги на основе различных критериев быстро и эффективно.
Удаление каталогов — это простой и легкий процесс, но вы должны быть осторожны, чтобы не удалить важные данные.
Источник
Find and Delete Empty Directories on the Linux Command Line
In this Linux quick tip we will be discussing how to find empty directories and how to delete them. We will also examine how to find empty files (zero size) and how to act on them as well.
Finding Empty Directories
Using the find command and a few options we can easily find empty directories. Let’s take a look at some sample commands, and then we will explain what each option means.
If I wanted to find empty directories in my home folder. I can do so with the following command.
Let’s break this down. First we call the find command, then we give it the path of the directory we want to search in (/home/savona/). Then we tell find to only look for directories (-type d) and finally we ask it to only return empty directories (-empty).
Finding Empty Files (zero-byte size)
We can use the same structure as above to find empty or zero-byte size files. This time instead of using d (directory) for the type, we will use f (file).
We can also use the size test to check if it is zero-byte size.
Deleting Empty Files and Directories
Using the find Command Delete Option
There are several ways to delete the empty files you find with the above command. The easiest is simply using the find command delete option (-delete).
The above will delete all empty directories it finds. To delete empty files, simply replace the type d (directory) with f (files).
Using the find Command Execute Option
Another option is to use the find command execute (-exec) option. This allows you to execute any command and use the items returned from the find command as arguments. Here is an example:
In the above command the curly brackets are used to denote the file name returned by find (the argument). The escaped semi-colon is an argument the command looks for to know when it is completed.
All following arguments to find are taken to be arguments to the command until an argument consisting of ;’ is encountered. The string <>’ is replaced by the current file name being processed everywhere it occurs in the arguments to the command.
Using xargs to Delete Arguments in Data Stream
Another option is to pipe the output of the find command into xargs. The xargs commands allow you to execute commands that are built from standard input, which in this case is replaced by the piped data from the find command.
In the above example, we are sending each filename found with the find command to the xargs command which is running rm to delete them.
If you want to delete directories with the xargs command, you have to change both the type option in find and the rm command to rmdir. Remember xargs just uses the input to build and run a command. If you run rm against a directory name, it will error out.
To learn more about standard input, pipes and redirection read “Introduction to Linux IO, Standard Streams, and Redirection“.
Conclusion
In this Linux quick tip we showed you how to find and delete empty directories and files on the Linux command line. We also covered using exec or xargs to act on files or directories returned by the find command. In a future article we will show you just how powerful these options can be.
Источник