- How to remove non empty Directory in Linux
- Procedure to remove non empty directory in Linux
- Examples for removing non empty directory under Linux
- How to get visual confirmation about deleting directory
- How to get confirmation prompt before every removal of a dir
- Conclusion
- Delete a non-empty directory when you get directory not empty error on Linux
- How to delete a non-empty directory in bash shell?
- If you get an error that read as ‘Permission denied’, try:
- Understanding rm command options
- Как удалить непустую директорию в Терминале?
- Используйте следующую команду:
- Если у пользователя нет прав на удаление папки:
- Delete / Remove a Directory Linux Command
- Commands to remove a directory in Linux
- rmdir command syntax to delete directory in Linux
- Delete directory Linux Command
- How to see a diagnostic message for every directory processed
- Removing directories with rmdir and wildcards
- Linux remove entire directory including all files and sub-directories command
- Are you getting permission denied error message while removing directories?
- Use find command to delete unwanted directories
- How to find and remove all empty directories
- Conclusion
- How to delete a non-empty directory in Terminal?
- 4 Answers 4
- Use the below command :
- In case user doesn’t have the permission to delete the folder:
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
Источник
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
- -r – Attempt to remove the file hierarchy rooted in each file argument i.e. recursively delete all files and sub-directories.
- -f – Force file delete operation.
- -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 делает его немного безопаснее, потому что он будет подсказывать вам при каждом удалении. Однако, если вы удаляете много файлов, это не будет очень практичным. Тем не менее, вы можете попробовать это в первую очередь.
Многие люди предлагают использовать -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:
- rmdir command – Deletes the specified empty directories and folders in Linux.
- 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.
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 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.
Источник