Linux delete directory recursive

UNIX: Recursive Delete Directory / Files

H ow do I delete (remove) a directory called $HOME/foo and its content including all files and sub-directories under Unix like operating systems? What is the best way to completely delete /tmp/foo/ with all it’s content?

Tutorial details
Difficulty level Easy
Root privileges No
Requirements rm
Est. reading time N/A

You need to use the rm command line utility to remove the files (and directories) specified on the command line. The following command will delete everything including subdires and file from the $HOME/foo directory. So be careful. You will not able to recover files or sub-dirs from the $HOME/foo directory. You have been warned. In order to delete directories, it is necessary to use the -r or -R option. This option recursively removes directories and their contents in the argument list passed to the rm command. The user is normally prompted for removal of any write-protected files in the directories unless the -f option is used by the end user. The syntax is 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

  1. -r or -R : Attempt to remove the file hierarchy rooted in $HOME/foo/ i.e. delete all directory’s contents including all files and sub-dirs.
  2. -f : Attempt to remove the files without prompting for confirmation, regardless of the file’s permissions.
  3. -i : Request confirmation before attempting to remove each file, regardless of the file’s permissions
See also

For more information, see the rm command man page by typing the following command:
$ man rm

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Как удалить каталог в 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 которая предложит вам только один раз, прежде чем продолжить удаление.

Чтобы удалить каталог, введите 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 Delete a Directory in Linux

Earlier in one of the tutorials, we have explained how to create directory in Linux. Now let’s check how to delete a directory in Linux which is either empty or having subdirectories with files. This is especially when you need to free up some space on your system in order to save more files or install additional packages.

There are many ways in which you can remove a directory in Linux. You can make use of the file manager if you are using a GUI system such as GNOME, MATE or KDE Plasma, or you can do it over the terminal.

When working with a GUI system deleting a directory takes it to the crash can, the equivalent of recycle bin in Windows from where it can be restored. However, the scenario is different when working on a command line on a minimal system because once a directory is deleted, it is permanently removed and cannot be recovered.

This tutorial will take you through various ways in which you can delete a directory in Linux.

Delete a directory using rmdir command

The rmdir command, short for’remove directory’, is a command-line tool that is used to delete empty directories. The operation will be successful if and only if the directory is empty. The syntax for deleting a directory is as follows:

For instance, to remove an empty directory called ‘mydirectory’, run the command:

If the directory is not empty, an error will be displayed on the screen as shown:

The error is a clear indication that the directory contains either files or folders or both.

Remove a directory using rm command

Short for remove, the rm command is used for deleting both empty and non-empty directories.

The rm command is usually used for removing files in Linux. However, you can pass some arguments that can help you delete directories. For example, to remove a directory recursively ( remove the directory alongside its contents), use the recursive option -r (-R or —recursive) as shown below.

If a directory is write-protected, you will be prompted whether to continue deleting the files inside the directory and the directory as a whole. To save you the annoyance and inconvenience of constantly bumping into such prompts, add the -f option to force the deletion without being prompted.

Additionally, you can delete multiple directories at a go in a single command as shown in the command below. The command deletes all the directories and their subdirectories without prompting for deletion.

To exercise more caution, you can use the -i option which prompts for the deletion of the directories and subdirectories. However, as we saw earlier, this can be quite annoying especially if you have several subfolders and files. To address this inconvenience, use the -I flag to prompt you only once.

When you hit y for ‘Yes’, the command will remove all the subfolders and files in the directory without prompting any further.

To remove an empty directory, pass the -d option as shown below.

Using find command

Find command is a command-line tool that helps users search for files as well as directories based on specific search criteria/pattern or expression. Additionally, the command can be used to search for directories and delete them based on the specified search criteria.

For example, to delete a directory called ‘mydirectory’ in the current directory, run the command below.

Let’s break down the parameters in the command

( . ) — This denotes the directory in which the search operation is being carried out. If you want to carry out the search in your current directory use the period sign (.)

-type d — This sets the search operation to search for directories only.

-name — This specifies the name of the directory.

-exec rm -rf — This deletes all directories and their contents.

<> +- — This appends all the files found at the end of the rm command.

Let’s take another example:

Remove an empty directory

If you wish to remove all empty directories use the following command:

Again, let’s break this down

. — This recursively searches in the current working directory

-type d — This keeps the search to directories only

-empty — This restricts the search pattern to empty directories only

-delete — This will delete all the empty directories found including subdirectories.

If you have lots of empty directories then use a shell script to delete empty directory.

Conclusion

In this tutorial, we looked at how to delete a directory in Linux using the rm, rmdir and find commands. We hope you can comfortably delete a directory in Linux whether it contains files and other subdirectories, or simply if it is empty. Give it a try and get back to us with your feedback.

Источник

Linux Delete Folder Recursively Command

rm command syntax to delete directories recursively

The syntax is as follows:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 2m

rm -r dirName
## OR ##
rm -r folderName
## OR ##
rm -rf folderName

Did you know?
Everything is a file in Linux and Unix-like systems. In other words, your pictures, documents, directories/folders, SSD/hard-drives, NIC, USB devices, keyboards, printers, and some network communications all are files.

Examples that examples how to delete folder recursively

In this example, recursively delete data folder in the current home directory:

The specified /home/vivek/data/ will first be emptied of any subdirectories including their subdirectories and files and then data directory removed. The user is prompted for removal of any write-protected files in the directories unless the -f (force) option is given on command line:

To remove a folder whose name starts with a — , for example ‘ —dsaatia ‘, use one of these commands:

We can add the -v option to see verbose outputs. In other words, the rm command will explain what is being done to our files and folders on Linux. For instance:
rm -rfv /path/to/dir1
rm -r -f -v /home/vivek/oldpartpics

Removing folders with names containing strange characters

Your folders and files may have while spaces, semicolons, backslashes and other chracters in Linux. For example:
ls -l
Let us say we have a folder named “ Our Sales Data ” and “ baddir# ” or “ dir2 ;# “. So how do we delete those directories with special names containing strange characters? The answer is simple. We try to enclose our troublesome filename or folder name in quotes. For example:
rm ‘Our Sales Data’
rm -rfv ‘/path/to/Dir 1 ;’
rm -r -f -v «baddir#»
rm a\ long \dir1 \name

Sometimes, we need insert a backslash ( \ ) before the meta-character in your filename or folder name:
rm \$dir1

  • 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

Deleting folder recursively command summary

rm command options for removing dirs/folders recursively
Command and options Description
-f Forceful option. Ignore nonexistent files and arguments, never prompt
-r remove directories and their contents recursively
-v Verbose output
rm — ‘-dir1’ Remove a dir/file whoes name start with a ‘ — ‘
rm ./-dir1 Same as above
rm -rfv ‘dir name here’ Enclose your troublesome filename/folder in quotes
rm -rfv \$dirname1 Same as above

See Linux rm(1) command man page or rm command example page for more information:
man rm
rm —help

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Читайте также:  Samsung np305e5a драйвера windows
Оцените статью