Linux terminal remove directory

How do I delete a directory in Linux terminal?

Let us see how to delete directories in Linux using the command line.

How to delete a directory in Linux terminal

Say you want to delete a directory named /home/vivek/data/, run:
rmdir /home/vivek/data/
rmdir -v

/data/
Verify directory deleted from the system with help of ls command:
ls /home/vivek/data/
ls

/data/
Please note that when attempting to remove a directory using the rmdir command, the directory must be empty. Otherwise, you might see an error message that read as follows on screen when execute rmdir -v /home/vivek/projects/ :

  • 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

How do I delete a full directory in Linux?

As I said earlier rmdir command remove the DIRECTORY(ies) if they are empty. But, how do you delete a full directory that has many files and sub-directories? The solutions is to pass the -rf option to the rm command. The syntax is:
rm -r dir1
rm -rf dir2 dir3 /path/to/foo/
rm -rfv /path/to/bar/dir/
rm -rfv /home/vivek/projects/

Where,

  • -r – Delete directories and their contents recursively
  • -f – Forceful option i.e. ignore nonexistent files and arguments, never prompt for anything
  • -v – Be verbose. Show what rmdir or rm command doing with given directory
  • -i – Prompt before every removal of file/dir
  • -I – Confirm (display prompt) once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes. Useful when working on a large number of files on Linux

Conclusion

This page showed how to delete both empty and non-empty directories along with all files/sub-directories using rm and rmdir command in Linux terminal application.

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

Источник

How do I force delete a directory in Linux?

How to force delete a directory in Linux

Here is how to forcefully delete a folder in Linux:

  1. Open the terminal application on Linux.
  2. The rmdir command removes empty directories only. Hence you need to use the rm command to remove files on Linux.
  3. Type the command rm -rf dirname to delete a directory forcefully.
  4. Verify it with the help of ls command on Linux.
Читайте также:  Microsoft watching you windows 10

Removing a directory that contains other files or directories

The syntax is as following for deleting a directory:
rm -rf dirName
Say you have a directory named /tmp/data/ that contains two files and one directory as follows:
ls -l /tmp/data/
If you run the rmdir command, you will get an error as follows:
rmdir /tmp/data/
As explained earlier rmdir only delete the DIRECTORIES, if they are empty. Therefore you must use the rm command to remove a full directory in Linux:
rm -rf /tmp/data/
Verify it:
ls -l /tmp/data/

Use rm command to delete a non-empty directory in Linux terminal

How do I remove a full directory in Linux with verbose output?

Pass the -v option to the rm command as follows:
rm -rfv dirname
For example, delete a full directory named /tmp/bar in Linux and note down the output on the screen:
rm -rfv /tmp/bar/

Where,

  • 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

  • -r : Recursive delete
  • -f : Force delete a directory
  • -v : Verbose output

Delete a non-empty directory in Linux terminal

In case if you don’t have the permission to delete the folder run rm command as a root user. Otherwise, you will see permission denied message on the screen. Therefore to avoid that prefix sudo at the beginning of the rm command :
sudo rm -rf dirName
OR
sudo rm -rf /somedir/
To remove a folder whose name starts with a ‘ — ‘, for example ‘-backups’, use one of these commands:
rm -rfv — -backups/
OR
rm -rfv ./-bacups/

Источник

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

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

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

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

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

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

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

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

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

rm -Rfv /var/www/public_html

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

Читайте также:  Откат с контрольной точки windows

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

sudo apt install wipe

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

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

Выводы

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

Источник

How to delete a non-empty directory in Terminal?

How do I delete the following directory?

This error comes up:

Is there a command to delete all the files in the directory and delete the directory folder?

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:

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

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.

Источник

How to remove non empty Directory in Linux

The following commands works with CentOS, RHEL, Fedora, Alpine, Arch, Debian, Ubuntu and all other Linux distros. Let us see some examples.

Procedure to remove non empty directory in Linux

We use the rm command to delete a directory that is not empty. The syntax is:
rm -rf dir-name
rm -rf /path/to/dir/name
Be careful when you use the rm command with -r and -f options. The -r option remove directories and their contents recursively including all files. The -f option to rm command ignore nonexistent files and arguments, never prompt for anything. There is no undo option. So you have to be very careful with rm -rf command. Let us see some examples.

Examples for removing non empty directory under Linux

Trying to remove trip-pictures directory with the rmdir command in Linx:
rmdir trip-pictures
Sample outputs:

To see files inside the directory use ls command ls -l trip-pictures
ls trip-pictures
To delete all files inside trip-pictures including folder itself run the following rm command:
rm -rf trip-pictures

How to get visual confirmation about deleting directory

Pass the -v to the rm command:
rm -vrf dir1
rm -vrf dir1 dir2
Sample outputs:

How to get confirmation prompt before every removal of a dir

You need to pass the -i option to the rm command:
rm -ir foo
Sample outputs:

To get prompt once before removing more than three files, or when removing recursively; less intrusive than -i , while still giving protection against most mistakes pass the -I option:
rm -Ir bar
Sample outputs:

Want to get info on all rm and rmdir switches? Try:
rm —help
rmdir —help

  • 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

Conclusion

You learned how to remove non empty directory under Linux or Unix-like operating systems using command line options. For more information see rm command and rmdir command command man pages by typing the following man command command:
man rm
man rmdir

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

Источник

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