Удаление папки линукс терминал

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».

Читайте также:  Узнать пароль суперпользователя linux

@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.

Источник

Use rm to Delete Files and Directories on Linux

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

This guide shows how to use rm to remove files, directories, and other content from the command line in Linux.

To avoid creating examples that might remove important files, this Quick Answer uses variations of filename.txt . Adjust each command as needed.

Читайте также:  Linux какие сигналы можно перехватывать

The Basics of Using rm to Delete a File

rm filename1.txt filename2.txt 

Options Available for rm

-i Interactive mode

Confirm each file before delete:

-f Force

-v Verbose

Show report of each file removed:

-d Directory

Note: This option only works if the directory is empty. To remove non-empty directories and the files within them, use the r flag.

-r Recursive

Remove a directory and any contents within it:

Combine Options

Options can be combined. For example, to remove all .png files with a prompt before each deletion and a report following each:

remove filename01.png? y filename01.png remove filename02.png? y filename02.png remove filename03.png? y filename03.png remove filename04.png? y filename04.png remove filename05.png? y filename05.png

-rf Remove Files and Directories, Even if Not Empty

Add the f flag to a recursive rm command to skip all confirmation prompts:

Combine rm with Other Commands

Remove Old Files Using find and rm

Combine the find command’s -exec option with rm to find and remove all files older than 28 days old. The files that match are printed on the screen ( -print ):

find filename* -type f -mtime +28 -exec rm '<>' ';' -print 

In this command’s syntax, <> is replaced by the find command with all files that it finds, and ; tells find that the command sequence invoked with the -exec option has ended. In particular, -print is an option for find , not the executed rm . <> and ; are both surrounded with single quote marks to protect them from interpretation by the shell.

This page was originally published on Tuesday, July 3, 2018.

Источник

Удаление файлов в Linux. Как удалять файл через терминал Linux?

Удаление файлов в Linux — задача, которая не вызывает затруднений у опытных пользователей. Наша же статься ориентирована, скорее, на начинающих. В ней вы сможете посмотреть, как удалить файлы через терминал, и какие команды лучше всего при этом использовать.

Почему лучше удалять файлы из консоли? Дело в том, что это даёт ряд преимуществ и бо́льшую гибкость. К примеру, используя специальную команду, вы легко и полностью удалите файл с жёсткого диска без возможности восстановления. Или всего одной командой и с помощью определённых символов, условий либо регулярных выражений удалите сотни не нужных вам файлов в каталоге либо подкаталогах, отвечающих некоторому критерию.

Читайте также:  Линукс скриншот части экрана

Удаляем файлы в Linux: практика

В ОС Linux для удаления файлов есть стандартная утилита rm . Как это принято со стандартными утилитами, в названии rm есть определённая идея. В нашем случае речь идёт о сокращении от английского слова Remove — удалять.

Итак, чтобы выполнить удаления одного файла, используем команду rm , указывая за ней имя нашего файла:

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

Бывает, что файл защищён от записи. Тогда нам предложат подтвердить команду. Чтобы удалить файл в такой ситуации, просто вводим y и нажимаем Enter.

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

Если мы хотим удалить сразу несколько файлов в Linux, то это тоже не проблема: используем команду rm , за которой прописываем имена наших файлов через пробел:

 
rm filename1 filename2 filename3

Ещё вариант — использование подстановочного знака * и регулярных выражений для соответствия определённым файлам. К примеру, мы легко удалим все файлы в Linux, имеющие расширение .txt следующей командой:

Для подтверждения каждого файла перед удалением используйте опцию -i :

Но когда файлов много, а вы твёрдо уверены в правильности своей команды и не хотите каждый раз отвечать на вопрос системы, используйте противоположную опцию -f . Будут удалены все файлы безоговорочно, т. е. без лишних вопросов:

Удаляем папки и каталоги в Linux

Если хотите удалить пустой каталог, задействуйте опцию -d .

Если хотим удалить непустой каталог и все файлы, которые в нём находятся, поступаем следующим образом:

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

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

 
rm -r dirname1 dirname2 dirname3

Кстати, здесь мы тоже можем использовать подстановочный знак ( *) и регулярные выражения, обеспечивающие соответствие нескольким каталогам.

Выводы

Как видите, удалить файл в Linux через терминал совсем несложно, поэтому с этой операцией справится каждый. При этом вы должны не только понимать, как правильно использовать команду rm в Linux, но и знать, как делать это безопасно.

Источник

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