Linux cmd delete dir

How do I remove a directory in Unix?

/Videos/ directory. You can use any one of the following commands to remove the directory in Unix (also known as a folder in Microsoft Windows operating system):

  1. rmdir command – Remove the specified empty directories on Unix
  2. rm command – Remove directories even if it is not empty in Unix

Let us see how to remove directories in Unix using the command line.

How do I remove a directory in Unix using the CLI?

The syntax is
rmdir dirNameHere
First, open the terminal Application. Say you want to remove a directory named banking-data in the home directory, run:
rmdir banking-data
OR
rmdir $HOME/banking-data
Verify directory deleted from the system with help of ls command:
ls
ls -l banking-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 /tmp/delta/ :

How to delete a directory in Unix even when it is not empty

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 -r option to the rm command. The rm command syntax is as follows to delete a directory in Unix:
rm -r /path/to/dir/
rm -rf myDirName
rm -rfv /path/to/dir
rm -rfv

  • 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 – Remove directories and their contents recursively on Unix
  • -f – Forceful option i.e. attempt to remove the files without prompting for confirmation, regardless of the file’s permissions.
  • -v – Be verbose. Show what rm command doing with given directory/file names on Unix
  • -i – Request confirmation before attempting to remove each file, regardless of the file’s permissions, or whether or not the standard input device is a terminal.

Conclusion

This page demonstrated how to delete both empty and non-empty directories along with all files/sub-directories using rm and rmdir command on Unix operating systems.

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

Источник

Delete / Remove a Directory Linux Command

Commands to remove a directory in Linux

There are two command to delete a folder in Linux:

  1. rmdir command – Deletes the specified empty directories and folders in Linux.
  2. rm command – Delete the file including sub-directories. You can delete non-empty directories with rm command in Linux.

Let us see some examples and usage in details delete the directories.

rmdir command syntax to delete directory in Linux

The rmdir command remove the DIRECTORY(ies), if they are empty. The syntax is:
rmdir directory-name
rmdir [option] directory-name
Open the terminal application and run command to delete given directory. For example, delete a folder named dir1:
rmdir dir1

Delete directory Linux Command

Open a command line terminal (select Applications > Accessories > Terminal), and then type the following command to remove a directory called /tmp/docs:
rmdir /tmp/docs
If a directory is not empty you will get an error message that read as follows:
rmdir letters
Sample outputs:

Читайте также:  Astroburn lite mac os

You can cd to the directory to find out and list all files:
$ cd letters
$ ls
Delete those files or directories. In this next example, remove data, foo and bar if bar were empty, foo only contained bar and data only contained foo directories:
cd /home/nixcraft
rmdir -p data/foo/bar

Where,

  • -p : Each directory argument is treated as a pathname of which all components will be removed, if they are empty, starting with the last most component.

How to see a diagnostic message for every directory processed

Pass the -v option to the rmdir command:
$ rmdir -v dir1
Sample outputs:

Removing directories with rmdir and wildcards

We can use wildcards such as ‘*’ and ‘?’ to match and delete multiple directories. For example:
$ ls -l dir*
We have three dirs named dir1, dir2, and dir3. To delete all directories starting with ‘dir’ in the current, you would use the following command:
rmdir -v dir*

Linux remove entire directory including all files and sub-directories command

To remove all directories and subdirectories use the rm command. For example, remove *.doc files and all sub-directories and files inside letters directory, type the following command:

Warning : All files including subdirectories will be deleted permanently when executed the following commands.

$ rm -rf letters/
Sample session:

Where,

  • -r : Attempt to remove the file hierarchy rooted in each file argument i.e. recursively remove subdirectories and files from the specified directory.
  • -f : Attempt to remove the files without prompting for confirmation, regardless of the file’s permissions

Are you getting permission denied error message while removing directories?

Only owners can delete their directories. However, a sysadmin can delete any directories created by anyone on the system. The syntax is:
sudo rmdir /path/to/dir/
sudo rm -rf dir2
When prompted, you need to provide root user or sudo user password.

Use find command to delete unwanted directories

Say you want to find out all directories named ‘session’ and delete them in the current directory, run:
find . -type d -iname ‘session’ -delete

  • 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 to find and remove all empty directories

Run:
find . -type d -iname ‘session’ -empty -delete
Where,

  • -type d : Only search for directories and ignore all other files.
  • -iname ‘session’ : Search directory named ‘session’. You can use wildcards here too. For example, -iname ‘dir*’ .
  • -empty : Only match empty directories
  • -delete : Deletes all found empty directories only

To delete all ‘.DS_store’ directories stored in /var/www/html, run:
sudo find /var/www/html/ -type d -name .DS_Store -exec rm <> \;
OR
sudo find /var/www/html/ -type d -name .DS_Store -exec rm <> +
The -exec option to the find command run an external command named rm to delete all files. The “ rm <> +/ ” is a better option as it uses one rm command to delete all .DS_Store directories.

Conclusion

This page showed how to delete a directory when it is empty. Further, it showed, how to remove folders using the rm and rmdir commands. See rm help page page for more info:

  • For more information read man pages: rm(1)

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

Источник

How to Delete a Directory in Linux

Earlier in one of the tutorials, we have explained how to create directory in Linux. Now let’s check how to delete a directory in Linux which is either empty or having subdirectories with files. This is especially when you need to free up some space on your system in order to save more files or install additional packages.

There are many ways in which you can remove a directory in Linux. You can make use of the file manager if you are using a GUI system such as GNOME, MATE or KDE Plasma, or you can do it over the terminal.

When working with a GUI system deleting a directory takes it to the crash can, the equivalent of recycle bin in Windows from where it can be restored. However, the scenario is different when working on a command line on a minimal system because once a directory is deleted, it is permanently removed and cannot be recovered.

Читайте также:  Амми админ для линукс

This tutorial will take you through various ways in which you can delete a directory in Linux.

Delete a directory using rmdir command

The rmdir command, short for’remove directory’, is a command-line tool that is used to delete empty directories. The operation will be successful if and only if the directory is empty. The syntax for deleting a directory is as follows:

For instance, to remove an empty directory called ‘mydirectory’, run the command:

If the directory is not empty, an error will be displayed on the screen as shown:

The error is a clear indication that the directory contains either files or folders or both.

Remove a directory using rm command

Short for remove, the rm command is used for deleting both empty and non-empty directories.

The rm command is usually used for removing files in Linux. However, you can pass some arguments that can help you delete directories. For example, to remove a directory recursively ( remove the directory alongside its contents), use the recursive option -r (-R or —recursive) as shown below.

If a directory is write-protected, you will be prompted whether to continue deleting the files inside the directory and the directory as a whole. To save you the annoyance and inconvenience of constantly bumping into such prompts, add the -f option to force the deletion without being prompted.

Additionally, you can delete multiple directories at a go in a single command as shown in the command below. The command deletes all the directories and their subdirectories without prompting for deletion.

To exercise more caution, you can use the -i option which prompts for the deletion of the directories and subdirectories. However, as we saw earlier, this can be quite annoying especially if you have several subfolders and files. To address this inconvenience, use the -I flag to prompt you only once.

When you hit y for ‘Yes’, the command will remove all the subfolders and files in the directory without prompting any further.

To remove an empty directory, pass the -d option as shown below.

Using find command

Find command is a command-line tool that helps users search for files as well as directories based on specific search criteria/pattern or expression. Additionally, the command can be used to search for directories and delete them based on the specified search criteria.

For example, to delete a directory called ‘mydirectory’ in the current directory, run the command below.

Let’s break down the parameters in the command

( . ) — This denotes the directory in which the search operation is being carried out. If you want to carry out the search in your current directory use the period sign (.)

-type d — This sets the search operation to search for directories only.

-name — This specifies the name of the directory.

-exec rm -rf — This deletes all directories and their contents.

<> +- — This appends all the files found at the end of the rm command.

Let’s take another example:

Remove an empty directory

If you wish to remove all empty directories use the following command:

Again, let’s break this down

. — This recursively searches in the current working directory

-type d — This keeps the search to directories only

-empty — This restricts the search pattern to empty directories only

-delete — This will delete all the empty directories found including subdirectories.

If you have lots of empty directories then use a shell script to delete empty directory.

Conclusion

In this tutorial, we looked at how to delete a directory in Linux using the rm, rmdir and find commands. We hope you can comfortably delete a directory in Linux whether it contains files and other subdirectories, or simply if it is empty. Give it a try and get back to us with your feedback.

Источник

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

Есть несколько различных способов удаления каталогов в системах Linux. Если вы используете файловый менеджер рабочего стола, такой как Gnome’s Files или KDE’s Dolphin, вы можете удалять файлы и каталоги с помощью графического пользовательского интерфейса менеджера. Но если вы работаете на автономном сервере или хотите удалить сразу несколько каталогов, лучшим вариантом является удаление каталогов (папок) из командной строки.

В этой статье мы объясним, как удалять каталоги в Linux с помощью команд rmdir , rm и find .

Подготовка

При удалении каталога с помощью файлового менеджера рабочего стола каталог фактически перемещается в корзину и может быть легко восстановлен.

Читайте также:  Linux system cpu time

Будьте особенно осторожны при удалении файлов или каталогов из командной строки, поскольку после удаления каталога с помощью команд, описанных в этой статье, его невозможно полностью восстановить.

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

Имена каталогов с пробелами должны быть экранированы обратной косой чертой ( / ).

Удаление каталогов с помощью rmdir

rmdir — это утилита командной строки для удаления пустых каталогов. Это полезно, когда вы хотите удалить каталог только в том случае, если он пуст, без необходимости проверять, пуст каталог или нет.

Чтобы удалить каталог с помощью rmdir , введите команду, а затем имя каталога, который вы хотите удалить. Например, чтобы удалить каталог с именем dir1 , введите:

Если каталог не пустой, вы получите следующую ошибку:

В этом случае вам нужно будет использовать команду rm или вручную удалить содержимое каталога, прежде чем вы сможете его удалить.

Удаление каталогов с помощью rm

rm — это утилита командной строки для удаления файлов и каталогов. В отличие от rmdir команда rm может удалять как пустые, так и непустые каталоги.

По умолчанию при использовании без каких-либо параметров rm не удаляет каталоги. Чтобы удалить пустой каталог, используйте параметр -d ( —dir ), а для удаления непустого каталога и всего его содержимого используйте параметр -r ( —recursive или -R ).

Например, чтобы удалить каталог с именем dir1 вместе со всем его содержимым, введите:

Если каталог или файл в каталоге защищен от записи, вам будет предложено подтвердить удаление. Чтобы удалить каталог без запроса, используйте параметр -f :

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

Параметр -i указывает rm запрашивать подтверждение удаления каждого подкаталога и файла. Если в каталоге много файлов, это может немного раздражать, поэтому вы можете рассмотреть возможность использования опции -I которая предложит вам только один раз, прежде чем продолжить удаление.

Чтобы удалить каталог, введите y и нажмите Enter .

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

Использование регулярных расширений при удалении каталогов может быть рискованным. Рекомендуется сначала перечислить каталоги с помощью команды ls чтобы вы могли видеть, какие каталоги будут удалены, прежде чем запускать команду rm .

Удаление каталогов с помощью find

find — это утилита командной строки, которая позволяет вам искать файлы и каталоги на основе заданного выражения и выполнять действие с каждым совпадающим файлом или каталогом.

Наиболее распространенный сценарий — использовать команду find для удаления каталогов на основе шаблона. Например, чтобы удалить все каталоги, которые заканчиваются на _cache в текущем рабочем каталоге, вы должны запустить:

Давайте проанализируем команду выше:

  • /dir — рекурсивный поиск в текущем рабочем каталоге ( . ).
  • -type d — ограничивает поиск каталогами.
  • -name ‘*_cache’ — искать только каталоги, заканчивающиеся на _cache
  • -exec — выполняет внешнюю команду с необязательными аргументами, в данном случае это rm -r .
  • <> + — добавляет найденные файлы в конец команды rm .

Удаление всех пустых каталогов

Чтобы удалить все пустые каталоги в дереве каталогов, выполните:

Вот объяснение используемых опций:

  • /dir — рекурсивный поиск в каталоге /dir .
  • -type d — ограничивает поиск каталогами.
  • -empty — ограничивает поиск только пустыми каталогами.
  • -delete — удаляет все найденные пустые каталоги в поддереве. -delete может удалять только пустые каталоги.

Используйте параметр -delete с особой осторожностью. Командная строка поиска оценивается как выражение, и если вы сначала добавите параметр -delete , команда удалит все, что находится ниже указанных вами начальных точек.

Всегда сначала проверяйте команду без опции -delete и используйте -delete в качестве последней опции.

/ bin / rm: слишком длинный список аргументов

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

Есть несколько разных решений этой проблемы. Например, вы можете cd в каталог и вручную или с помощью цикла для удаления Подкаталогов один за другим.

Самое простое решение — сначала удалить все файлы в каталоге с помощью команды find а затем удалить каталог:

Выводы

С помощью rm и find вы можете быстро и эффективно удалять каталоги по различным критериям.

Удаление каталогов — простой и легкий процесс, но вы должны быть осторожны, чтобы не удалить важные данные.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

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