- Linux / UNIX: How To Empty Directory
- How To Empty Directory In Linux and Unix
- Linux Empty Directory Using the rm Command
- Delete All Files Using the Find Command
- How to remove a full directory and all files in Linux
- Conclusion
- linux-notes.org
- Удалить пустые файлы и директории в Unix/Linux
- Удалить пустые файлы в Unix/Linux
- Удалить пустые директории в Unix/Linux
- Как удалить каталог Linux
- Как удалить каталог Linux
- Выводы
- Delete / Remove a Directory Linux Command
- Commands to remove a directory in Linux
- rmdir command syntax to delete directory in Linux
- Delete directory Linux Command
- How to see a diagnostic message for every directory processed
- Removing directories with rmdir and wildcards
- Linux remove entire directory including all files and sub-directories command
- Are you getting permission denied error message while removing directories?
- Use find command to delete unwanted directories
- How to find and remove all empty directories
- Conclusion
Linux / UNIX: How To Empty Directory
How To Empty Directory In Linux and Unix
- rm command – Delete one or more files or directories.
- find command – Find and delete all files from a specific directory.
Linux Empty Directory Using the rm Command
First, consider the following directory structure displayed using the tree command
To delete all files from /tmp/foo/ directory (i.e. empty /tmp/foo/ directory), enter:
$ cd /tmp/foo/
$ rm *
OR
$ rm /tmp/foo/*
Delete All Files Using the Find Command
Consider the following directory structure:
To delete all files from /tmp/bar/ directory (including all files from sub-directories such as /tmp/bar/dir1), enter:
$ cd /tmp/bar/
$ find . -type f -delete
OR
$ find /tmp/bar/ -type f -delete
The above find command will delete all files from /tmp/bar/ directory. It will not delete any sub-directories. To remove both files and directories, try:
find /path/to/target/dir/ -delete
The find commands options are as follows:
- 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 ➔
- -type f : Delete on files only.
- -type d : Remove folders only.
- -delete : Delete all files from given directory name.
How to remove a full directory and all files in Linux
To remove a directory that contains other files or sub-directories, use the following rm command command. In the example, I am going to empty directory named “docs” using the rm -rf command as follows:
rm -rf /tmp/docs/*
Get verbose outputs:
rm -rfv /tmp/docs/*
The rm command options are as follows:
- -r : Delete directories and their contents recursively on Linux or Unix-like systems.
- -f : Forceful removal. In other words, ignore nonexistent files and delete whatever found.
- -v : Verbose outputs. For example, explain what is being done on screen.
Conclusion
You learned how to use the rm and find command to delete all files and sub-directories on Linux/macOS/*BSD and Unix-like systems. In other words, this is useful to empty folders on Linux. For more information see rm command help page here.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
linux-notes.org
Удалить пустые файлы и директории в Unix/Linux
Решил написать статью о там как можно удалить пустые файлы и директории в ОС — Linux. Я покажу и расскажу как это можно сделать в своей статье «Удалить пустые файлы и директории в Linux» и приведу готовые примеры как можно удалить все пустые файлы или директории в определенной папке. Делается это через командную строку с использованием команд: find, rm и rmdir.
Сейчас откроем терминал (командную строку) и перейдем в ту папку, в которой вам нужно удалить все пустые файлы:
Удалить пустые файлы в Unix/Linux
Для начала, посмотрим список имеющихся пустых файлов. Для этого, я буду использовать команду find и укажу ей (передам параметр), что мне нужно найти только файлы (за это отвечает параметр «-type f») и что данные файлы должны быть пустыми (за это отвечает параметр «-empty») в текущей моей папки:
Теперь, я воспользуюсь аргументом «-exec», он дает возможность выполнить определенную команду над списком файлов. Я передам в «exec» то, что хочу выполнить команду «rm» (удалить файлы) для пустых файлов:
Удалить пустые директории в Unix/Linux
Для начала, я проверю какие папки у меня не содержат файлов. Для этого, я так же буду использовать команду «find» с параметром «-empty», но указываю тип поиска «-type d» (поиск папок):
Сейчас мне необходимо их удалить. Передаю аргументу «-exec» команду rmdir (удаление папок) для того чтобы удалить все имеющиеся пустые папки:
Еще можно использовать:
Или еще по-простому:
Статья «Удалить пустые файлы и директории в Unix/Linux» подошла к завершению.
Источник
Как удалить каталог Linux
В операционной системе Linux можно выполнить большинство действий через терминал. Удаление каталога Linux — это достаточно простое действие, которое можно выполнить просто открыв файловый менеджер.
Однако в терминале это делается немного быстрее и вы получаете полный контроль над ситуацией. Например, можете выбрать только пустые папки или удалить несколько папок с одним названием. В этой статье мы рассмотрим как удалить каталог Linux через терминал.
Как удалить каталог Linux
Существует несколько команд, которые вы можете использовать для удаления каталога Linux. Рассмотрим их все более подробно. Самый очевидный вариант — это утилита rmdir. Но с помощью нее можно удалять только пустые папки:
Другая команда, которую можно применить — это rm. Она предназначена для удаления файлов Linux, но может использоваться и для папок если ей передать опцию рекурсивного удаления -r:
Такая команда уже позволяет удалить непустой каталог Linux. Но, можно по-другому, например, если вы хотите вывести информацию о файлах, которые удаляются:
rm -Rfv моя_папка
Команда -R включает рекурсивное удаление всех подпапок и файлов в них, -f — разрешает не удалять файлы без запроса, а -v показывает имена удаляемых файлов. В этих примерах я предполагаю что папка которую нужно удалить находится в текущей рабочей папке, например, домашней. Но это необязательно, вы можете указать полный путь к ней начиная от корня файловой системы:
rm -Rfv /var/www/public_html
Читайте подробнее про пути в файловой системе в статье путь к файлу Linux. Теперь вы знаете как удалить непустой каталог в консоли linux, далее усложним задачу, будем удалять папки, которые содержат определенные слова в своем имени:
find . -type d -name «моя_папка» -exec rm -rf <> \;
Подробнее про команду find смотрите в отдельной статье. Если кратко, то -type d указывает, что мы ищем только папки, а параметром -name задаем имя нужных папок. Затем с помощью параметра -exec мы выполняем команду удаления. Таким же образом можно удалить только пустые папки, например, в домашней папке:
/ -empty -type d -delete
Как видите, в find необязательно выполнять отдельную команду, утилита тоже умеет удалять. Вместо домашней папки, можно указать любой нужный вам путь:
find /var/www/public_html/ -empty -type d -delete
Перед удалением вы можете подсчитать количество пустых папок:
find /var/www/public_html/ -empty -type d | wc -l
Другой способ удалить папку linux с помощью find — использовать в дополнение утилиту xargs. Она позволяет подставить аргументы в нужное место. Например:
/ -type f -empty -print0 | xargs -0 -I <> /bin/rm «<>«
Опция -print0 выводит полный путь к найденному файлу в стандартный вывод, а затем мы передаем его команде xargs. Опция -0 указывает, что нужно считать символом завершения строки \0, а -I — что нужно использовать команду из стандартного ввода.
Если вы хотите полностью удалить папку Linux, так, чтобы ее невозможно было восстановить, то можно использовать утилиту wipe. Она не поставляется по умолчанию, но вы можете ее достаточно просто установить:
sudo apt install wipe
Теперь для удаления каталога Linux используйте такую команду:
Опция -r указывает, что нужно удалять рекурсивно все под папки, -f — включает автоматическое удаление, без запроса пользователя, а -i показывает прогресс удаления. Так вы можете удалить все файлы в папке linux без возможности их восстановления поскольку все место на диске где они были будет несколько раз затерто.
Выводы
В этой статье мы рассмотрели как удалить каталог linux, а также как удалить все файлы в папке linux без возможности их будущего восстановления. Как видите, это очень просто, достаточно набрать несколько команд в терминале. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
Delete / Remove a Directory Linux Command
Commands to remove a directory in Linux
There are two command to delete a folder in Linux:
- rmdir command – Deletes the specified empty directories and folders in Linux.
- rm command – Delete the file including sub-directories. You can delete non-empty directories with rm command in Linux.
Let us see some examples and usage in details delete the directories.
rmdir command syntax to delete directory in Linux
The rmdir command remove the DIRECTORY(ies), if they are empty. The syntax is:
rmdir directory-name
rmdir [option] directory-name
Open the terminal application and run command to delete given directory. For example, delete a folder named dir1:
rmdir dir1
Delete directory Linux Command
Open a command line terminal (select Applications > Accessories > Terminal), and then type the following command to remove a directory called /tmp/docs:
rmdir /tmp/docs
If a directory is not empty you will get an error message that read as follows:
rmdir letters
Sample outputs:
You can cd to the directory to find out and list all files:
$ cd letters
$ ls
Delete those files or directories. In this next example, remove data, foo and bar if bar were empty, foo only contained bar and data only contained foo directories:
cd /home/nixcraft
rmdir -p data/foo/bar
Where,
- -p : Each directory argument is treated as a pathname of which all components will be removed, if they are empty, starting with the last most component.
How to see a diagnostic message for every directory processed
Pass the -v option to the rmdir command:
$ rmdir -v dir1
Sample outputs:
Removing directories with rmdir and wildcards
We can use wildcards such as ‘*’ and ‘?’ to match and delete multiple directories. For example:
$ ls -l dir*
We have three dirs named dir1, dir2, and dir3. To delete all directories starting with ‘dir’ in the current, you would use the following command:
rmdir -v dir*
Linux remove entire directory including all files and sub-directories command
To remove all directories and subdirectories use the rm command. For example, remove *.doc files and all sub-directories and files inside letters directory, type the following command:
Warning : All files including subdirectories will be deleted permanently when executed the following commands.
$ rm -rf letters/
Sample session:
Where,
- -r : Attempt to remove the file hierarchy rooted in each file argument i.e. recursively remove subdirectories and files from the specified directory.
- -f : Attempt to remove the files without prompting for confirmation, regardless of the file’s permissions
Are you getting permission denied error message while removing directories?
Only owners can delete their directories. However, a sysadmin can delete any directories created by anyone on the system. The syntax is:
sudo rmdir /path/to/dir/
sudo rm -rf dir2
When prompted, you need to provide root user or sudo user password.
Use find command to delete unwanted directories
Say you want to find out all directories named ‘session’ and delete them in the current directory, run:
find . -type d -iname ‘session’ -delete
- 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 ➔
How to find and remove all empty directories
Run:
find . -type d -iname ‘session’ -empty -delete
Where,
- -type d : Only search for directories and ignore all other files.
- -iname ‘session’ : Search directory named ‘session’. You can use wildcards here too. For example, -iname ‘dir*’ .
- -empty : Only match empty directories
- -delete : Deletes all found empty directories only
To delete all ‘.DS_store’ directories stored in /var/www/html, run:
sudo find /var/www/html/ -type d -name .DS_Store -exec rm <> \;
OR
sudo find /var/www/html/ -type d -name .DS_Store -exec rm <> +
The -exec option to the find command run an external command named rm to delete all files. The “ rm <> +/ ” is a better option as it uses one rm command to delete all .DS_Store directories.
Conclusion
This page showed how to delete a directory when it is empty. Further, it showed, how to remove folders using the rm and rmdir commands. See rm help page page for more info:
- For more information read man pages: rm(1)
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник