Delete dir with files linux

How do I remove a directory and all its contents?

The following command will do it for you. Use caution though if this isn’t your intention as this also removes files in the directory and subdirectories.

«-f» is «—force» which overrides some sanity checks and prompting. A safer command to start with would be rm -r directoryname .

@JimParis I think the word «safer» is relative. Suppose you are writing a script to run on a remote computer. That script has a command which is supposed to remove a directory. Here, it would be «safer» to use rm -rf directoryname coz you wouldn’t want your script to pause execution, because it’s waiting for user input. Of course, you have to be sure that deleting the directory would do no harm.

if rm -rf directoryname fails you, try using rm -R -f directoryname , or rm —recursive -f directoryname .

If you are not having any luck with these, you should consider reinstalling rm or switching shells.

These were the options available on my rm man page, I looked it up by typing man rm to view my options on recursive deletion and the force options.

Does your rm man page list -r ? What does it do? (Try it in a directory that you create just for testing purposes, with only dummy files (and maybe subdirectories) in it.) What operating system are you using?

P.S. If rm -r doesn’t work, that would be an OS issue, not a shell issue. (Strictly speaking, it would be an issue with the version of rm that you’re using, so you could address it by installing a different version of rm , or searching your system to see whether you already have a different version of rm in some directory other than /bin .)

Ah, right. I forgot to mention I’m on Ubuntu 14.04 When I ran man rm in my terminal, it gave me a text file with the less text viewer. I scrolled found an indented entry with a whole that had the -R and —recursive options cozied up with the -r option, signifying that all of those arguments are identical.

edit: have you tried sudo rm -r directoryName ? The unwritten rules of the basic commands is that -r will allow a program to run recursively on every file your filesystem (starting where ever you choose!) and that -f will forcefully do things, even if it’s dangerous. ‘cd’, ‘mv’, ‘ls’ mostly holds this principle true. ls -r / is gonna be a duzie, and cp -rf / /dev/null will destroy everything on your filesystem.

Other answers show how to completely remove a directory’s content, but IMO they don’t address the literal question of the original post — that is, how can one delete subdirectories (as opposed to usual files). In other words, how can one delete empty directory structures while keeping subdirectories containing files ?

This can be achieved with find :

find directoryname -type d -delete 

This command will recursively search for directories ( -type d ) through directoryname and -delete them only if their subdirectories or themselves don’t contain any files.

Читайте также:  Operating system logs 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

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

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 без возможности их будущего восстановления. Как видите, это очень просто, достаточно набрать несколько команд в терминале. Если у вас остались вопросы, спрашивайте в комментариях!

Читайте также:  Check directory sizes linux

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

Источник

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

Ilenia Magoni

Ilenia Magoni

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.

image-98

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:

image-99

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.

image-106

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:

image-107

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

image-109

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.

image-108

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.

Читайте также:  Linux просмотр всех дисков

Enjoy this new tool in your arsenal!

Источник

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.

Источник

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