Linux deleting directory with files

Как удалить каталог в Linux

Есть несколько различных способов удаления каталогов в системах Linux. Если вы используете файловый менеджер рабочего стола, такой как Gnome’s Files или KDE’s Dolphin, вы можете удалять файлы и каталоги с помощью графического пользовательского интерфейса менеджера. Но если вы работаете на автономном сервере или хотите удалить сразу несколько каталогов, лучшим вариантом является удаление каталогов (папок) из командной строки.

В этой статье мы объясним, как удалять каталоги в Linux с помощью команд rmdir , rm и find .

Подготовка

При удалении каталога с помощью файлового менеджера рабочего стола каталог фактически перемещается в корзину и может быть легко восстановлен.

Будьте особенно осторожны при удалении файлов или каталогов из командной строки, поскольку после удаления каталога с помощью команд, описанных в этой статье, его невозможно полностью восстановить.

В большинстве файловых систем Linux для удаления каталога требуется разрешение на запись в каталог и его содержимое. В противном случае вы получите ошибку «Операция запрещена».

Имена каталогов с пробелами должны быть экранированы обратной косой чертой ( / ).

Удаление каталогов с помощью rmdir

rmdir — это утилита командной строки для удаления пустых каталогов. Это полезно, когда вы хотите удалить каталог только в том случае, если он пуст, без необходимости проверять, пуст каталог или нет.

Чтобы удалить каталог с помощью rmdir , введите команду, а затем имя каталога, который вы хотите удалить. Например, чтобы удалить каталог с именем dir1 , введите:

Если каталог не пустой, вы получите следующую ошибку:

В этом случае вам нужно будет использовать команду rm или вручную удалить содержимое каталога, прежде чем вы сможете его удалить.

Удаление каталогов с помощью rm

rm — это утилита командной строки для удаления файлов и каталогов. В отличие от rmdir команда rm может удалять как пустые, так и непустые каталоги.

По умолчанию при использовании без каких-либо параметров rm не удаляет каталоги. Чтобы удалить пустой каталог, используйте параметр -d ( —dir ), а для удаления непустого каталога и всего его содержимого используйте параметр -r ( —recursive или -R ).

Например, чтобы удалить каталог с именем dir1 вместе со всем его содержимым, введите:

Если каталог или файл в каталоге защищен от записи, вам будет предложено подтвердить удаление. Чтобы удалить каталог без запроса, используйте параметр -f :

Чтобы удалить сразу несколько каталогов, вызовите команду rm , после которой укажите имена каталогов, разделенные пробелом. Приведенная ниже команда удалит все перечисленные каталоги и их содержимое:

Параметр -i указывает rm запрашивать подтверждение удаления каждого подкаталога и файла. Если в каталоге много файлов, это может немного раздражать, поэтому вы можете рассмотреть возможность использования опции -I которая предложит вам только один раз, прежде чем продолжить удаление.

Читайте также:  Команда find linux exec

Чтобы удалить каталог, введите y и нажмите Enter .

Вы также можете использовать обычные расширения для сопоставления и удаления нескольких каталогов. Например, чтобы удалить все каталоги первого уровня в текущем каталоге, который заканчивается на _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 с особой осторожностью. Командная строка поиска оценивается как выражение, и если вы сначала добавите параметр -delete , команда удалит все, что находится ниже указанных вами начальных точек.

Всегда сначала проверяйте команду без опции -delete и используйте -delete в качестве последней опции.

/ bin / rm: слишком длинный список аргументов

Это сообщение об ошибке появляется, когда вы используете команду rm для удаления каталога, содержащего огромное количество файлов. Это происходит из-за того, что количество файлов превышает системное ограничение на размер аргумента командной строки.

Есть несколько разных решений этой проблемы. Например, вы можете cd в каталог и вручную или с помощью цикла для удаления Подкаталогов один за другим.

Самое простое решение — сначала удалить все файлы в каталоге с помощью команды find а затем удалить каталог:

Выводы

С помощью rm и find вы можете быстро и эффективно удалять каталоги по различным критериям.

Удаление каталогов — простой и легкий процесс, но вы должны быть осторожны, чтобы не удалить важные данные.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How to Remove Files and Directories in Linux Command Line [Beginner’s Tutorial]

How to delete a file in Linux? How to delete a directory in Linux? Let’s see how to do both of these tasks with one magical command called rm.

How to delete files in Linux

Let me show you various cases of removing files.

1. Delete a single file

If you want to remove a single file, simply use the rm command with the file name. You may need to add the path if the file is not in your current directory.

If the file is write protected i.e. you don’t have write permission to the file, you’ll be asked to confirm the deletion of the write-protected file.

You can type yes or y and press enter key to confirm the deletion. Read this article to know more about Linux file permissions.

2. Force delete a file

If you want to remove files without any prompts (like the one you saw above), you can use the force removal option -f.

3. Remove multiple files

To remove multiple files at once, you can provide all the filenames.

Читайте также:  Puppy linux tor browser

You can also use wildcard (*) and regex instead of providing all the files individually to the rm command. For example, if you want to remove all the files ending in .hpp in the current directory, you can use rm command in the following way:

4. Remove files interactively

Of course, removing all the matching files at once could be a risky business. This is why rm command has the interactive mode. You can use the interactive mode with the option -i.

It will ask for confirmation for each of the file. You can enter y to delete the file and n for skipping the deletion.

You just learned to delete files. Let’s see how to remove directory in Linux.

How to remove directories in Linux

There is a command called rmdir which is short for remove directory. However, this rmdir command can only be used for deleting empty directories.

If you try to delete a non-empty directory with rmdir, you’ll see an error message:

There is no rmdir force. You cannot force rmdir to delete non-empty directory.

This is why I am going to use the same rm command for deleting folders as well. Remembering rm command is a lot more useful than rmdir which in my opinion is not worth the trouble.

1. Remove an empty directory

To remove an empty directory, you can use the -d option. This is equivalent to the rmdir command and helps you ensure that the directory is empty before deleting it.

2. Remove directory with content

To remove directory with contents, you can use the recursive option with rm command.

This will delete all the contents of the directory including its sub-directories. If there are write-protected files and directories, you’ll be asked to confirm the deletion.

3. Force remove a directory and its content

If you want to avoid the confirmation prompt, you can force delete.

4. Remove multiple directories

You can also delete multiple directories at once with rm command.

Summary

Here’s a summary of the rm command and its usage for a quick reference.

Purpose Command
Delete a single file rm filename
Delete multiple files rm file1 file2 file3
Force remove files rm -f file1 file2 file3
Remove files interactively rm -i *.txt
Remove an empty directory rm -d dir
Remove a directory with its contents rm -r dir
Remove multiple directories rm -r dir1 dir 2 dir3

I hope you like this tutorial and learned to delete files and remove directories in Linux command line. If you have any questions or suggestions, please leave a comment below.

Источник

Delete / Remove a Directory Linux Command

Commands to remove a directory in Linux

There are two command to delete a folder in Linux:

  1. rmdir command – Deletes the specified empty directories and folders in Linux.
  2. 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

Источник

Читайте также:  Windows 10 не находит драйвера веб камеры
Оцените статью