How to delete folder in linux terminal

How to Remove a Directory in Linux

Removing a directory in Linux is a pretty simple task if you are using the GUI. However, if you don’t have access to the GUI, you can also remove directories using terminal commands.

In this tutorial, we will show you how to remove a directory in Linux via commands in the terminal window or command line.

How to remove directories in Linux

  • A system running a Linux distribution.
  • An account with sudo privileges.
  • Access to the terminal window or command line.

Note: For other Linux directory management articles, see How to Move Directories in Linux and How to Rename a Directory in Linux.

How to Remove a Directory in Linux?

There are two Linux commands you can use to remove a directory from the terminal window or command line:

  • The rm command removes complete directories, including subdirectories and files.
  • The rmdir command removes empty directories.

It is important to note that the rm and rmdir commands permanently remove directories without moving them to the Trash directory. This means that you cannot restore a directory removed using these commands.

Note: Even though rm and rmdir permanently remove files and directories, users with enough skill and time still have a chance of restoring some of the removed files. If you want to learn more about removing files permanently, have a look at our shred command tutorial.

rm Command

The rm command in Linux removes files and directories.

It uses the following syntax:

rm [options] [file or directory name]

Note: To remove multiple files or directories using the rm command, add multiple file or directory names, separated by blank spaces.

The different rm command options include:

  • — f : Forces the removal of all files or directories.
  • -i : Prompts for confirmation before removing.
  • -I : Prompts once before removing more than three files or when removing recursively.
  • -r : Removes directories and their content recursively.
  • -d : Removes empty directories.
  • -v : Provides a verbose output.
  • —help : Displays the help text.
  • —version : Displays the command version.

Trying to use the rm command without any options to remove a directory results in an error message:

An error message displays when you try to remove a directory using the rm command without options

If you want to remove an empty directory, add the -d flag to the rm command:

Note: If you want to remove a directory whose name starts with a hyphen (), use the rm — [directory name] or rm ./[directory name] syntax.

The example below shows that the rm command with the — d flag removes the Example directory:

Removing an empty directory using the rm command

Use the -r flag to delete a directory that contains subdirectories and files.

Читайте также:  Linux mint official wallpaper

The image below shows the tree hierarchy of the Example directory, which contains Dir1 and Dir2 subdirectories, with multiple text files in each:

An example of a directory and file hierarchy

Using the -r flag removes the entire directory, including subdirectories and files, while the -v flag lists each step of the process as the output:

Recursively removing multiple directories, subdirectories, and files using the rm command

The -i option displays a prompt asking you to confirm directory removal. Type Y and press Enter to confirm.

Displaying a prompt as the output when removing a directory

Write-protected directories require user input when deleting. Create such a directory with:

To remove the directory, use:

rm -d write protected directory

Type Y and press Enter to confirm deletion. To avoid the confirmation, use the -f flag or elevate the command privileges to sudo:

If the write-protected directory contains other files and directories, use the following command:

Note: rm -rf / is a dangerous Linux command that forces a recursive deletion on the root directory, rendering your system unusable.
Avoid using -f and sudo while removing directories, unless you know what you’re doing. To learn more about this command, visit our article What Is sudo rm -rf in Linux and Is It Dangerous.

rmdir Command

The Linux rmdir command removes empty directories only. The command uses the following syntax:

rmdir [options] [directory name]

The rmdir command includes the following options:

  • —ignore-fail-on-non-empty : Doesn’t show an error message when trying to remove a non-empty directory.
  • -p : Removes the directory along with its parent in the hierarchy.
  • -v : Provides a verbose output.
  • —help : Displays help text.
  • —version : Displays the command version.

Using the rmdir command on a non-empty directory produces an error:

Using the rmdir command on a non-empty directory

In this case, the Example directory contains the Test subdirectory:

Showing the hierarchy of the Example directory

To remove these directories using the rmdir command, add them in reverse order of hierarchy. Using the -v option lists each step of the process as the output:

rmdir -v Example/Test Example

Removing multiple directories with the rmdir command

A simpler method of doing this is to use the -p option with the subdirectory’s name. This removes both the subdirectory and its hierarchical parent:

Removing a subdirectory and its parent using the rmdir command

The rmdir command allows you to remove multiple directories with similar names using wildcards. For instance, if you want to remove directories named Example1, Example2, and Example3:

Using wildcards with the rmdir command to remove multiple directories

After reading this tutorial, you should be able to remove directories in Linux using commands in the terminal window or command line.

To learn more about other commands in Linux, check out our Linux commands cheat sheet.

Источник

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.

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.

Читайте также:  Linux mint oem mode

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.

Источник

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

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

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

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

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

Читайте также:  Linux увеличение системного раздела

Другая команда, которую можно применить — это 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

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

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.

Источник

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