Command deleting folders linux

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

В операционной системе Linux можно выполнить большинство действий через терминал. Удаление каталога Linux — это достаточно простое действие, которое можно выполнить просто открыв файловый менеджер.

Однако в терминале это делается немного быстрее и вы получаете полный контроль над ситуацией. Например, можете выбрать только пустые папки или удалить несколько папок с одним названием. В этой статье мы рассмотрим как удалить каталог Linux через терминал.

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

Существует несколько команд, которые вы можете использовать для удаления каталога Linux. Рассмотрим их все более подробно. Самый очевидный вариант — это утилита rmdir. Но с помощью нее можно удалять только пустые папки:

Другая команда, которую можно применить — это rm. Она предназначена для удаления файлов Linux, но может использоваться и для папок если ей передать опцию рекурсивного удаления -r:

Такая команда уже позволяет удалить непустой каталог Linux. Но, можно по-другому, например, если вы хотите вывести информацию о файлах, которые удаляются:

Команда -R включает рекурсивное удаление всех подпапок и файлов в них, -f — разрешает удалять файлы без запроса, а -v показывает имена удаляемых файлов. В этих примерах я предполагаю что папка которую нужно удалить находится в текущей рабочей папке, например, домашней. Но это необязательно, вы можете указать полный путь к ней начиная от корня файловой системы:

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

find . -type d -name «моя_папка» -exec rm -rf <> \;

Подробнее про команду find смотрите в отдельной статье. Если кратко, то -type d указывает, что мы ищем только папки, а параметром -name задаем имя нужных папок. Затем с помощью параметра -exec мы выполняем команду удаления. Таким же образом можно удалить только пустые папки, например, в домашней папке:

find ~/ -empty -type d -delete

Как видите, в find необязательно выполнять отдельную команду, утилита тоже умеет удалять. Вместо домашней папки, можно указать любой нужный вам путь:

find /var/www/public_html/ -empty -type d -delete

Перед удалением вы можете подсчитать количество пустых папок:

Читайте также:  Nano editor on linux

find /var/www/public_html/ -empty -type d | wc -l

Другой способ удалить папку linux с помощью find — использовать в дополнение утилиту xargs. Она позволяет подставить аргументы в нужное место. Например:

find ~/ -type f -empty -print0 | xargs -0 -I <> /bin/rm «<>«

Опция -print0 выводит полный путь к найденному файлу в стандартный вывод, а затем мы передаем его команде xargs. Опция -0 указывает, что нужно считать символом завершения строки \0, а -I — что нужно использовать команду из стандартного ввода.

Если вы хотите полностью удалить папку Linux, так, чтобы ее невозможно было восстановить, то можно использовать утилиту wipe. Она не поставляется по умолчанию, но вы можете ее достаточно просто установить:

Теперь для удаления каталога Linux используйте такую команду:

Опция -r указывает, что нужно удалять рекурсивно все под папки, -f — включает автоматическое удаление, без запроса пользователя, а -i показывает прогресс удаления. Так вы можете удалить все файлы в папке linux без возможности их восстановления поскольку все место на диске где они были будет несколько раз затерто.

Выводы

В этой статье мы рассмотрели как удалить каталог linux, а также как удалить все файлы в папке linux без возможности их будущего восстановления. Как видите, это очень просто, достаточно набрать несколько команд в терминале. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Remove a Directory in Linux – Delete a Folder Command

Dillion Megida

Dillion Megida

How to Remove a Directory in Linux – Delete a Folder Command

If you’re using a user interface, you can right-click on a directory and select «Delete» or «Move to Bin». But how do you do this on the terminal? I’ll explain that in this article.

How to Remove a Directory in Linux

There are two ways to remove directories in Linux: the rm and rmdir commands.

The TL;DR of both commands is that rm deletes directories that may contain content such as files and subdirectories, while rmdir ONLY deletes empty directories.

Also, both commands delete directories permanently (rather than moving them to the trash), so be careful when using them.

Let’s look at both commands in more detail.

How to Use the Linux rm command

You use the rm command to delete files and directories in Linux. For directories, this command can be used to delete a directory entirely – that is, it deletes a directory and all files and subdirectories within the directory.

Here’s the syntax of this command:

rm [options] [files and/or directories] 

To remove a file, say test.txt , you can use the command without options like this:

For directories, you have to provide some flag options.

How to delete a folder with contents

For a directory with contents, you have to provide the -r flag. Without using this flag like this:

You will get this error: rm: test: is a directory

Читайте также:  Lids linux intrusion detection system

The -r flag informs the rm command to recursively delete the contents of a directory (whether it’s files or subdirectories). So, you can delete a directory like this:

How to delete an empty folder

For an empty folder, you can still provide the -r flag, but the dedicated -d flag applies to this case. Without this flag, you will get the same error rm: [folder]: is a directory.

To delete an empty directory, you can use this command:

It is recommended to use the -d flag for empty directory cases instead of the -r flag because the -d flag ensures that a directory is empty.

If it is not empty, you will get the error rm: test: Directory not empty. So, to be sure you are performing the proper empty directory operation, use the -d flag.

How to Use the Linux rmdir Command

The rmdir command is specifically used to delete empty directories. The syntax is:

It is the equivalent of the rm command with the -d flag: rm -d .

When you use rmdir on a non-empty directory, you get this error: rmdir: [folder]: Directory not empty.

To delete an empty directory, use this command without options:

The rmdir command also has the -p flag, which allows you to delete a directory along with its parent in the tree. For example, if you have this file structure:

In this case, Test is a directory that has the Test2 subdirectory. If you delete the Test2 directory, Test becomes an empty directory. So instead of doing:

rmdir Test/Test2 Test # deleting Test2 and then Test 

You can use the -p flag like this:

This command will delete Test2 and afterward delete Test, the parent in the tree. But this command will throw an error if either directory is not empty.

How to Delete Directories that Match a Pattern in Linux

You can also use rm and rmdir with glob patterns. Globbing is similar to Regex, but the former is used for matching file names in the terminal.

For example, if you want to delete the directories test1, test2, and test3, instead of running:

rm -r test1 test2 test3 # or if they are empty rmdir test1 test2 test3 

You can use a wildcard glob pattern like this:

rm -r test* # or if they are empty rmdir test* 

The asterisk * matches any mixture of characters after the «test» word. You can also apply other glob patterns. Learn more in the globbing documentation

Wrap Up

Now you know how to delete directories in Linux from the command line. You learned about the rm and rmdir commands and when to use each.

Источник

Remove Directory in Linux – How to Delete a Folder from the Command Line

Zaira Hira

Zaira Hira

Remove Directory in Linux – How to Delete a Folder from the Command Line

Linux CLI is a powerful tool that can help you accomplish complex tasks.

Читайте также:  Kvm linux установка centos

One of the common operations you’ll need to perform is to delete things. Just as like creating files and folders, deleting them from the Linux command line is something you’ll do often.

In this post, we will discuss how to delete directories from the command line. We will discuss the syntax along with some examples. I am using Ubuntu in these examples.

Syntax of the Linux rm Command

You use the rm command to delete something from the command line in Linux. The syntax of the rm command looks like this:

Some important flags you’ll need to use when deleting a directory are as follows:

  • -r , -R , —recursive [«Recursion»] – Removes directories and their contents recursively.
  • -v , —verbose [«Verbose»] – This option outputs the details of what is being done on the CLI.
  • -f , —force [«Force»] – This option ignores nonexistent files and never prompts you.
  • -i [«Interactive»] – Use this flag when you want to be prompted before every removal.
  • -d [«Directory] – This works only when the directory is empty.

⚠ Be careful when using the rm command️ and always make sure that any important data is backed up.

How to identify a folder to remove

As we are discussing how to delete folders, we need to be pretty sure that we are actually deleting a folder. We can identify a folder/directory with the d flag in the first column. Notice that files have the first flag as — .

image-55

Examples of Linux rm command

In our current folder, we have 2 folders CSharpLab and PythonLab . Their content is shown below.

image-48

Note that CSharpLab is an empty directory.

How to delete a folder that’s not empty

Let’s delete the PythonLab folder first.

image-53

  • -r recursively deletes all files and folders. Note in the output below, all files ( man.py, calculator.py, palindrome.py ) and folders ( /lib ) were removed.
  • -v shares details.
  • -i makes deletion interactive, which means it will ask before removing anything.

How to delete an empty folder

Let’s try to delete the CSharpLab folder. As this folder is empty, we can use the -d flag.

image-50

How to use the -f «force» flag

Let’s now see how the -f flag works. This forces the deletion of folders without any prompts or warnings. In case of an error, -v still ignores, and deletes the files that are valid.

In the example below, there is a typo in the folder name. Note that the typo is ignored. The original file is intact.

image-51

Wrapping up

Removing directories is useful when you need to remove folders after archiving them, when deleting duplicates, when deleting unused folders, and much more.

All these tasks are targeted at creating more disk space. I hope you found this blog helpful.

Источник

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