Delete directory with file linux

Remove a Directory in Linux – How to Delete Directories and Contents From the Command Line

Linux is a popular open source operating system, and its features are often available in your development environment. If you can learn its basic commands, it’ll make your life as a developer much easier.

In this guide you will learn how to delete directories and files from the Linux command line.

The Linux rm Command

The rm (short for remove) command is pretty useful. Let’s learn its syntax and look at a few examples to see it in action.

rm Command Syntax

The syntax is shown below, with args being any number of arguments (folders or files).

Without options you can use it to delete files. But to delete directories you need to use the options for this command.

The options are as follows:

  • -r , «recursive» – this option allows you to delete folders and recursively remove their content first
  • -i , «interactive» – with this option, it will ask for confirmation each time before you delete something
  • -f , «force» – it ignores non-existent files and overrides any confirmation prompt (essentially, it’s the opposite of -i ). It will not remove files from a directory if the directory is write-protected.
  • -v , «verbose» – it prints what the command is doing on the terminal
  • -d , «directory» – which allows you to delete a directory. It works only if the directory is empty.

Linux rm Command Example

Let’s take a project_folder directory as an example. It has these files and folders inside:

Let’s use this directory to show how the various options work.

You can add the option -v to all commands so that it will write down step by step what’s going on.

So, let’s start with the first option, -r . You just learned that this removes files and folders recursively. You can use it like this rm -r project_folder or also rm -rv project_folder as the verbose option.

It has deleted the project_folder directory and everything inside it, in the order shown.

Let’s recreate the folder and try again.

What happens if you don’t use the -r option and you try to delete the directory anyway? It will not allow it and will instead show an error:

To delete directories you can use the -d option, but if you try to use it in this case it will give an error as the folder is not empty.

The -i option make so that it asks about each action individually.

And you need to press y or n and then Enter after each query.

If you select y for all queries it will delete everything:

If instead you decide to not delete some files or folders, with n it will keep those files and continue with the rest:

The last option we haven’t seen so far is -f , which will suppress errors.

For example writing as below you would be trying to delete two non existing files – there is not a rat.png file, and dog.pmg has a typo and it gives two errors. With the -f option, you will not see the errors.

Conclusion

The Linux command line is pretty useful if you’re a developer. In this article, you have seen one of its possible commands, rm , that you can use to delete directories and files.

Источник

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.

Читайте также:  Wordpress что такое single page

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:

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

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:

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:

You can use a wildcard glob pattern like this:

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.

Источник

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.

Читайте также:  Картридж механической очистки k740

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

How to Remove (Delete) Directory in Linux

В этой статье мы расскажем , как удалить каталоги в Linux , используя mdir, rm и find команду.

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

Читайте также:  Join трех таблиц postgresql

Прежде чем вы начнете

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

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

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

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

Удаление каталогов с rmdir

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

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

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

Удаление каталогов с rm

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

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

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

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

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

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

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

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

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

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

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

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

Вывод

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

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

Источник

КомпСовет