Removing folders in linux

How to delete a non-empty directory in Terminal?

I’m unable to remove a directory like «New Folder» using all the above detailed commands. It’s double worded. But I want to remove that directory. Any suggestions will be welcomed. T.Divakara, Bengaluru, India

Its the blank space in the file name, try using ‘quotes’ > rmdir ‘New Folder’ < then the folder disapers, or use escape characters for non-vissible characters.

4 Answers 4

Use the below command :

It deletes all files and folders contained in the lampp directory.

In case user doesn’t have the permission to delete the folder:

Add sudo at the beginning of the command :

Otherwise, without sudo you will be returned permission denied. And it’s a good practice to try not to use -f while deleting a directory:

Note: this is assuming you are already on the same level of the folder you want to delete in terminal, if not:

sudo rm -r /path/to/folderName 

FYI: you can use letters -f , -r , -v :

  • -f = to ignore non-existent files, never prompt
  • -r = to remove directories and their contents recursively
  • -v = to explain what is being done

In my humble opinion, it’s a good practice never to add the «f» on first attempt. Its purpose is to ignore certain warning prompts that may be important, especially if you’ve accidentally done it on/from the wrong directory. In my opinion it’s good to try without the «f» first, then only if you are encountering a lot of warning prompts and you’re sure it’s OK to ignore them all, Ctrl+C out of it and repeat the command with the «f».

@thomasrutter . Agree. A file «xxx» owner: root and group: root can BE deleted with the -f switch; and without sudo. This is the message without -f: «rm: remove write-protected regular file ‘/home/william/.cache/netbeans/v08.01/tmp/xxx’? _». _Tread gently.

However, you need to be careful with a recursive command like this, as it’s easy to accidentally delete a lot more than you intended.

It is a good idea to always double-check which directory you’re in, and whether you typed the command correctly, before pressing Enter.

Safer version

Adding -i makes it a little safer, because it will prompt you on every deletion. However, if you are deleting many files this is not going to be very practical. Still, you can try this first.

Many people suggest using -f (combining it into -Rf or -rf ), claiming that it gets rid of annoying prompts. However, in normal cases you don’t need it, and using it suppresses some problems that you probably do want to know about. When you use it, you won’t be warned if your arguments supply a non-existing directory or file(s): rm will just silently fail to delete anything. As a general rule, try first without the -f : if there are problems with your arguments, then you’ll notice. If you start getting too many prompts about files without write access, then you can try it with -f . Alternatively, run the command from a user (or the superuser using sudo) that has full permissions to the files and directories you’re deleting to prevent these prompts in the first place.

Читайте также:  Узнать версию docker linux

Источник

Terminal Basics #6: Delete Files and Folders in Linux

You have learned to create files and directories. Now it is time to learn about deleting files and folders in the command line.

In the earlier chapters of the Terminal Basics series, you learned to create new files and directories (folders). Let’s now see how you can delete files and folders in the Linux terminal.

Deleting files

Removing files in Linux terminal

You won’t see any output if the file is successfully deleted. Here’s an example where I removed one of the files named new_file . When I list the directory contents, you can see that new_file no longer exists. You can also remove multiple files in the same command:

Deleting multiple files in single rm command

Let me show an example of deleting two files in a single command.

🏋️Exercise file deletion

mkdir practice_delete && cd practice_delete

Do you see a message ‘remove write protected file‘? That’s because you removed the write permission (for modification) from this file. You can press Y or enter key to confirm the deletion or N to deny the removal. If you don’t want to see this message and still delete it, you can use the force delete option -f . Try it by deleting file1 :

Here’s a replay of all the above examples to help you:

There is no trash bin in the Linux command line. Once the file is deleted, you cannot undo the action to bring it back from the trash bin as you do in the graphical file manager. For this reason, be extra careful while deleting the files.

Remove but with caution

The lack of trash bin makes the deletion a permanent jobs of sort. This is why you should be careful about what files are you deleting. There is an interactive mode with option -i . With this, you’ll be asked to confirm the deletion.

This is helpful when you are deleting several files based on a certain pattern. Here’s an example where I am interactively deleting all the files that match file_ pattern in their name. I delete some and keep some in the interactive mode.

I advise switching to the directory where the files are located and then removing them. This helps in reducing any potential caused by a typo in file path.

Deleting directories

However, it can only delete empty directories. If the directory has any files or subdirectories in it, the rmdir command will throw error.

[email protected]:~/practice_delete$ rmdir dir2 rmdir: failed to remove 'dir2': Directory not empty

And that makes it less useful in most cases. So, how do you delete a non-empty folder then? Well, you use the same rm command that you used earlier for removing files. Yes, the same rm command but with the recursive option -r :

🏋️Exercise folder deletion

Let’s practice what you learned. Switch to practice_delete folder if you are not already there. Now, create two directories dir1 and dir2.

Читайте также:  Open firefox in linux

Since the dir2 is not empty, rmdir command will fail. Instead, use the rm command with recursive option:

Here’s a replay of all the above command examples to help you out:

The interactive deletion mode is even more helpful while deleting a directory with the recursive option of the rm command: rm-ri dir_name

So, you learned to delete files and folders both using Linux commands. It’s time to practice some more.

Test your knowledge

. ├── dir1 │ ├── file1 │ ├── file2 │ └── file3 ├── dir2 ├── dir3 └── file 
  • Delete file2 .
  • Switch to the dir3 and force delete the file named file in the upper directory.
  • Delete all the contents of dir1 but not the directory itself.
  • List the contents of the dir .

I encourage you to discuss the practice questions in the It’s FOSS community forum.

This is going good. You have learned several basic things like switching directories, checking contents of directory, creating and deleting files and directories. In the next chapter, you’ll learn about copying files and folders in the terminal. Stay tuned!

Источник

Как удалить каталог 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 необязательно выполнять отдельную команду, утилита тоже умеет удалять. Вместо домашней папки, можно указать любой нужный вам путь:

Читайте также:  Add java home linux

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.

Источник

How to Remove Files and Directories Using Linux Command Line

This tutorial, will show you how to use the rm , unlink , and rmdir commands to remove files and directories in Linux.

How to Remove Files #

To remove (or delete) a file in Linux from the command line, use either the rm (remove) or unlink command.

The unlink command allows you to remove only a single file, while with rm , you can remove multiple files at once.

Be extra careful when removing files or directories, because once the file is deleted it cannot be easily recovered.

    To delete a single file, use the rm or unlink command followed by the file name:

If the file is write-protected, you will be prompted for confirmation, as shown below. To remove the file type y , and hit Enter . Otherwise, if the file is not write-protected, it will be deleted without prompting.

 rm: remove write-protected regular empty file 'filename'?
rm filename1 filename2 filename3

You can also use a wildcard ( * ) and regular expansions to match multiple files. For example, to remove all .pdf files in the current directory, use the following command:

How to Remove Directories (Folders) #

In Linux, you can remove/delete directories with the rmdir and rm .

rmdir is a command-line utility for deleting empty directories, while with rm you can remove directories and their contents recursively.

    To remove an empty directory, use either rmdir or rm -d followed by the directory name:

rm -r dirname1 dirname2 dirname3

Conclusion #

By now you should have a good understanding of how to use the Linux rm , rmdir and unlink commands and you should be able to safely remove files and directories from the command line.

Feel free to leave a comment if you have any questions.

Источник

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