How to delete folders linux

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

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

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

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

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

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

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

rm -Rfv моя_папка

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

rm -Rfv /var/www/public_html

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

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

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

/ -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. Она позволяет подставить аргументы в нужное место. Например:

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

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

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

Читайте также:  Установка windows 10 с диска второй системой

sudo apt install wipe

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

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

Выводы

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

Источник

How do I remove a folder?

I am a new user and I am trying to remove a specific folder. I am using sudo rm /path/ , but it is not working. What is the correct command to use?

It is a file catolog I am attempting to remove but I am geting a message that it is empty.

6 Answers 6

Be sure the folder is really empty (hidden files/folders might be in there). Look at the file contents again with

If you’re absolutely certain that it doesn’t contain anything you want to have (including subdirectories), delete it with

  • -r is for recursive, so it will delete the folder and subfolders, even if it is non-empty
  • -f is for force (this might be unnecessary).

One thing to note is that the folder should be empty, then run the following command

Another thing to note is that the command your are typing should not start with a slash(/) not unless the folder is under root.

The last option and you should be very careful while using this one, is to force removal of the directory in question including any other files/directories in it.

For a beginner I would not recommend getting into the habit of using rm -Rf or rm -r -f , this will bite you in the face sooner or later. Safer would be to create a systemwide alias. Open terminal: Ctrl + Alt + T , then type:

So you get prompted before wiping out all your vacation photo’s by accident. The second recommendation I would like to add is to use rmdir , it will complain about non-empty directories and that is exactly what you want as a newbee.

But in the sense of the question, the answer is as given here already, use -f to erase a folder.

If you are sure that the directory exists, then:

To delete the entire directory to your folders and files

Источник

How to Delete Files and Folders in Linux

Linux command line fundamentals are absolutely essential for every future system administrator and advanced Linux user. Today we’ll cover another basic function – deleting files and directories in Linux using the command line.

The rmdir Command

The command used to delete empty directories in Linux is rmdir.

The basic syntax of this command is easy to grasp. here’s an example:

  • rmdir is the command
  • [option] is an optional modifier that changes the way the command behaves
  • DirectoryName is the directory you want removed
Читайте также:  Clam антивирус для линукс

If no option is provided, rmdir simply deletes the directory whose name is provided as the destination. Before using this command, you’ll have to log into your VPS server using SSH. Here’s an article to help you out.

Remove Folders in Linux Using the rmdir Command

Before using the rmdir command we suggest you check the files present in a directory with the ls command. In our case, we have a directory named Dir1.

This command will delete the empty directory named Dir1. Simple enough, right?

You can also delete multiple directories by separating their names by spaces. For instance:

After executing this command, the directories named Dir1, Dir2 and Dir3 will be deleted.

Let say we have a directory named Dir3. Dir3 has subdirectories and files inside of it. Now if we use following command:

We will receive an error like this:

As you may have guessed from the output, rmdir only works with empty directories.

The rmdir is a smart utility, and only allows you to delete empty directories as a built-in safeguard to prevent accidental loss of data. Remember it’s almost impossible to recover deleted data on any Linux distribution.

The -p option lets you delete the directory as well as its parent directories.

This above command will delete Dir3 and its parent directories Dir2 and Dir1.

The -v option outputs a diagnostic text for every directory processed. Using this option will output a confirmation listing all the directories that were deleted.

The rm Command

The rmdir command is great for safely removing unused and empty directories. If you want to remove files or directories containing files, you would have to use the rm command.

The basic syntax of this command is similar to rmdir:

Remove Files in Linux Using the rm Command

Use the rm command to remove the file named article.txt:

If we have a directory with the name Dir1 containing subdirectories and files we will have to attach the -r modifier. The command would look like this:

The -r option recursively removes directories and their content.

Another helpful option is -i. This will ask you to confirm the files that will be deleted individually. That way you can avoid any unpleasant mistakes.

You can also delete empty directories using -d option. The following command will delete an empty directory with name Dir1:

You can use a wildcard (*) and a regular expansions to match multiple files. For instance, the following command will delete all pdf files placed in the current directory.

You can use variation of all the commands listed above to delete files with other extensions like .txt, .doc, .odt, etc.

The -f option lets you forcefully delete everything placed in a directory. The command would look like this:

The above command will delete everything recursively and forcefully, residing under the Dir1 directory without prompting anything on the terminal.

You can also delete more than one directory at a time. The following command will delete three directories Dir1, Dir2 and Dir3 in a single command.

Congratulations, you successfully mastered all the basic functions of the rm and rmdir commands!

Wrap Up

In Linux deleting a single file by accident can lead to major issues. That’s why it’s essential to master the two main commands for file and directory removal – rm and rmdir. In this article we cover these two commands and the various options that can be used with them.

Читайте также:  Графические среды для linux mint

We hope you found this article useful! Remember, once you delete a file or directory from Linux, you can’t recover it, so be extra careful! Good luck.

Edward is an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward’s goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.

Источник

Linux Delete Folder Using rmdir and rm Command

Linux delete folder using rmdir

Let us see some examples that show how to remove a folder in Linux.

Linux remove folder

In this example, delete the directory called /tmp/letters/
rmdir /tmp/letters
For example, the following command would remove two empty folders named alpha and delta in the current directory:
rmdir alpha delta

How to get additional information about what is happening when running rmdir

Pass the -v (verbose) option as follows:
rmdir -v dir1
rmdir -v foo bar

Remove Folder and Its Ancestors

The -p option can delete directory and its subdirectories/sub-folders:
rmdir -p dir1/dir2/dir3
Where rmdir command command options are as follows:

  • -p : Linux remove folder i.e. remove the parent folders of the specified directory
  • -v : Output a diagnostic for every directory processed
  • —ignore-fail-on-non-empty : Ignore each failure that is solely because a folder is non-empty.

Delete All Files and Folders Including Subdirectories

Use the following syntax:
rm -rf /path/to/dir
For example, delete /home/vivek/docs and all its subdirectories including files, enter:

  • 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

Where rm command options are as follows,

  • -r : Recursively delete a directory by first deleting all of its contents
  • -f : Linux delete folder forcefully
  • -v : Verbose output

GUI File Manager

The Nautilus file manager (GNOME desktop) provides a simple and integrated way to manage your files and applications. Just open it from Places menu and select folder and hit delete key.

Fig.01: Gnome File Browser

Conclusion

In this tutorial, you learned how to delete folders in the Linux using rmdir and rm command-line options. The rmdir command is used to remove empty folders in Linux. The rm command used to delete both files and folders even if they are not empty. See rmdir help page here for more info.

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

Источник

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