Remove non empty directory linux

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

Читайте также:  Max performance windows 10

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

Источник

Delete a non-empty directory when you get directory not empty error on Linux

I am trying to remove a directory named data in my $HOME. However, I am getting an error that read as ‘ rmdir: data/: Directory not empty ‘. How do I delete a non-empty directory in bash terminal running on Linux operating system?

Yes, you can use any one of the following command to delete all the files in the directory and remove the directory itself including all files on Linux operating system.

Open the Terminal app and type the following command.

How to delete a non-empty directory in bash shell?

The syntax is (be careful all files will be deleted forever):
rm -rf
rm -rfFor example, the following will deletes all files and sub-directories contained in the movies directory your home directory. Run rm command:
rm -rfv movies
OR
rm -rfv $HOME/movies

If you get an error that read as ‘Permission denied’, try:

In case if you do not have the permission to delete the directory run command as root user using the sudo command:
sudo rm -rfv movies
OR
sudo rm -rfv $HOME/movies
OR
sudo rm -rfv /path/to/data/dir/
Sample session:

Fig.01: How to delete a non-empty directory in Linux bash shell terminal?

  • 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

Understanding rm command options

  1. -r – Attempt to remove the file hierarchy rooted in each file argument i.e. recursively delete all files and sub-directories.
  2. -f – Force file delete operation.
  3. -v – Be verbose when deleting files, showing them as they are removed.

The rmdir command delete directory (folder) provided it is empty. Use rm command to delete the non-empty directory on Linux.

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

Источник

Как удалить непустую директорию в Терминале?

Как мне удалить следующий каталог?

Эта ошибка появляется:

Есть ли команда удалить все файлы в каталоге и удалить папку каталога?

Используйте следующую команду:

Удаляет все файлы и папки, содержащиеся в lampp каталоге.

Если у пользователя нет прав на удаление папки:

Добавьте sudo в начале команды:

В противном случае sudo вам будет отказано в разрешении. И хорошей практикой является попытка не использовать ее -f при удалении каталога:

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

FYI: Вы можете использовать буквы -f , -r , -v :

  • -f = игнорировать несуществующие файлы, никогда не запрашивать
  • -r = рекурсивно удалять каталоги и их содержимое
  • -v = объяснить, что делается

Тем не менее, вы должны быть осторожны с такой рекурсивной командой, как это, так как легко случайно удалить намного больше, чем вы предполагали.

Рекомендуется всегда дважды проверять, в каком каталоге вы находитесь, и правильно ли вы ввели команду, прежде чем нажимать Enter.

Более безопасная версия

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

Читайте также:  Hp ink tank wireless 419 драйвера windows 10

Многие люди предлагают использовать -f (объединяя его в -Rf или -rf ), утверждая, что он избавляется от раздражающих подсказок. Тем не менее, в обычных случаях вам это не нужно, и его использование подавляет некоторые проблемы, о которых вы, вероятно , хотите знать. Когда вы используете его, вы не будете предупреждены, если ваши аргументы содержат несуществующий каталог или файл (ы): rm просто молча не сможет ничего удалить. Как правило, попробуйте сначала без -f : если есть проблемы с вашими аргументами, то вы заметите. Если вы начинаете получать слишком много запросов о файлах без прав записи, то вы можете попробовать это с -f , В качестве альтернативы, запустите команду от пользователя (или суперпользователя, использующего sudo), у которого есть полные права доступа к удаляемым файлам и каталогам, чтобы в первую очередь предотвратить появление этих запросов.

Источник

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:

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.

Читайте также:  Windows make any window always on top

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 Remove a Non-Empty Directory in Linux

In this guide, check out how to remove non-empty directories in Linux.

Removing a Directory in Linux

First, let’s have a look at how to remove directories in Linux.

Removing an Empty Directory

In this example, I have set an empty directory:

To remove the directory, we can use rmdir:

Removing a Non-Empty Directory

When it comes to a non-empty directory, the previously mentioned methods won’t work.

Here, I’ve set a non-empty directory for demonstration:

Try to remove normally, use the following command:

To remove the non-empty directory, use the following rm command instead:

  • -r: Instructs rm to recursively delete the contents of the directory, both the files and sub-directories.
  • -v: Instructs rm to run in verbose mode.

If you don’t want any prompt for action, then add the flag “-f”, as well:

If you want to have prompts for actions, then use the flag “-i” instead. Note that rm will ask for all the files and sub-directories it’s about to remove:

Instead of “-i”, the flag “-I” is less intrusive while still protecting against mistakes:

Conclusion

In Linux, removing a directory is different than removing files. The removal tools and methods are also different depending on whether the target directory is empty or not. This guide demonstrates how to remove both empty and non-empty directories. Note that the directories and the data contained within and removed in this manner will have no way of being recovered except by using special tools and methods. Thus, before removing, ensure that it’s not something important.

The man pages of rm and rmdir contain further information about various supported options:

Источник

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