Linux fast remove directory

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.

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.

Читайте также:  Что занимает память mac os

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

Источник

Linux Delete Folder Recursively Command

rm command syntax to delete directories recursively

The syntax is as follows:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 2m

rm -r dirName
## OR ##
rm -r folderName
## OR ##
rm -rf folderName

Did you know?
Everything is a file in Linux and Unix-like systems. In other words, your pictures, documents, directories/folders, SSD/hard-drives, NIC, USB devices, keyboards, printers, and some network communications all are files.

Examples that examples how to delete folder recursively

In this example, recursively delete data folder in the current home directory:

The specified /home/vivek/data/ will first be emptied of any subdirectories including their subdirectories and files and then data directory removed. The user is prompted for removal of any write-protected files in the directories unless the -f (force) option is given on command line:

To remove a folder whose name starts with a — , for example ‘ —dsaatia ‘, use one of these commands:

We can add the -v option to see verbose outputs. In other words, the rm command will explain what is being done to our files and folders on Linux. For instance:
rm -rfv /path/to/dir1
rm -r -f -v /home/vivek/oldpartpics

Removing folders with names containing strange characters

Your folders and files may have while spaces, semicolons, backslashes and other chracters in Linux. For example:
ls -l
Let us say we have a folder named “ Our Sales Data ” and “ baddir# ” or “ dir2 ;# “. So how do we delete those directories with special names containing strange characters? The answer is simple. We try to enclose our troublesome filename or folder name in quotes. For example:
rm ‘Our Sales Data’
rm -rfv ‘/path/to/Dir 1 ;’
rm -r -f -v «baddir#»
rm a\ long \dir1 \name

Sometimes, we need insert a backslash ( \ ) before the meta-character in your filename or folder name:
rm \$dir1

  • 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

Deleting folder recursively command summary

rm command options for removing dirs/folders recursively
Command and options Description
-f Forceful option. Ignore nonexistent files and arguments, never prompt
-r remove directories and their contents recursively
-v Verbose output
rm — ‘-dir1’ Remove a dir/file whoes name start with a ‘ — ‘
rm ./-dir1 Same as above
rm -rfv ‘dir name here’ Enclose your troublesome filename/folder in quotes
rm -rfv \$dirname1 Same as above

See Linux rm(1) command man page or rm command example page for more information:
man rm
rm —help

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

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/

Источник

Which is the fastest method to delete files in Linux

Creating, deleting, and modifying files is one of the common task that a user does in any operating system. This kind of task comes under a day to day list of tasks that a user does. Although it is quite fast and seamless operation when it comes to deleting a single or a handful of files in Linux or any other operating system. But if the number of files is quite large, then the deletion operation takes quite long to complete.

What happens when you delete a file in Linux, depends on the kind of file system, on which the file you want to delete resides. There are many operational differences in deleting files under different types of file system. When we talk about files in Linux, its all about inodes rather than files. How an inode gets modified, during file deletion is an important aspect to understand.

Inodes are the building blocks of Linux operating system. If you are interested in understanding inodes, i would recommend reading the below post, before going ahead, as we will not be discussing inode related details in this post.

I am writing this post, to find out the fastest method to delete large number of files in Linux. We will begin this tutorial with some simple file deletion methods, and then will compare the speed with which different method completed the task of file deletion. Another major reason for writing this post is the time i spend on one of our crawler servers, to delete millions of files with very small size (few KBs).

As i told, if you are dealing with small number of files, then the operation will be fast compared to a large number of files which are of very small size. Let’s begin this with some simple commands in Linux used to delete files.

Commands to delete files in Linux and their example usage

To delete files in Linux, the most commonly used command is rm command. Let’s see some example’s of rm command.

-f used in the above command, will delete the file forcefully without asking for a confirmation.

The above command will delete the directory named «testdirectory» as well as all the contents inside that directory(-r option used is to delete files recursively)

The above command rmdir, will only delete the directory if its empty.

Let’s now have a look at some different methods of deleting files in Linux. One of my favorite methods out there is to use find command. Find commands is a very handy tool that can be used to search files according to its type, size, created date, modified date, and much more different criteria. To find out more about this wonderful searching tool in Linux, read the below post.

The above shown command, will delete all the files inside /test directory. First the find command will look for all files inside the directory, and then for each result, it will execute and rm.

Let’s see some different methods that can be used with find command, to delete files.

In the above shown example, find command will search all those files inside the /test directory which are modified 7 days ago, and then delete each of them.

Above shown example, will search for all those files in the directory /test which are larger than 7M, and then delete each of them.

In all of the above shown examples of find command, rm command is invoked for each and every file in the list. For example, in the last find command shown above, if the result is 50 files which are bigger than 7M, then 50 rm commands are invoked for deleting each of them. This will take a much longer time.

Instead of using the above command of rm with the help of -exec argument in find, there is a better alternative. We will see the alternative and then calculate the difference between speed in each of them.

As i told before, the main idea behind finding the deletion speed, is when you delete large number of files. So lets first create half a million files with the help of a simple bash for loop. And after creating half a million files, we will try to delete it with rm command, find command with exec argument and then will see a better find command alternative .

The above command will create 5 lakh files (half a million) in the current working directory, with the name 1.txt to 500000.txt, and each file contains the text «testing», so the file size will be at least in the range of some kilo bytes. Let’s now test the speed of deleting these number of files with different commands. First let’s use the simple rm command, and then will use find command with -exec and then delete option to calculate the time taken to delete these number of files.

If you see the above rm command i ran on the test directory, containing half a million files, it gave me a message saying /bin/rm: Argument list too long . Which means the command didn’t complete the deletion, because the number of files given to rm command was too big to complete. So rm command didn’t even stand the test, because it gave up. Don’t pay attention to the time displayed by the time command, because rm command didn’t complete its operation, and time command displays the output without bothering about the end result of the command.

Now let’s use our previously seen find command with -exec argument.

From the output we got by using time command, it is clear that it took 14 minutes and 51 seconds to delete 5 lakh files from a single directory. This is quite a long time, because for each file a separate rm command is executed, until the complete list of files gets deleted.

Now lets test the time consumed, by using -delete, option in find command.

Wow you saw that result!! -delete option only took 5 minutes 11 seconds. That’s a wonderful improvement in the speed, when you delete millions of files in Linux.

Let’s now have a look at how deleting files using Perl language works, and its speed compared to other options we saw earlier.

That’s insanely fast compared to other find command, and rm command options we saw earlier. Till now this seems to be the best method that can be used to delete all the files in a directory. That’s a remarkable achievement in speed for deleting files in Linux. If you see the output Perl only took around 1 minute to delete half a million files in that directory.

But yeah if you are interested in finding more complex options while using Perl, you need to have some good hands on with Perl regular expressions.

There is one more lesser used and less known method that can be used to delete large number of files inside a folder. This method is none other than our famous tool RSYNC used for transferring and synchronizing files between two local as well as remote locations in Linux.

Let’s have a look at that method of deleting all files inside a folder with the help of RSYNC command. The method and logic used behind deleting files with the help of rsync is based on the fact that rsync is commonly used for synchronizing files between two different locations.

This can be achieved by simply synchronizing a target directory which has the large number of files, with an empty directory. In our case test directory has half a million files, lets create a directory called as blanktest , which will be kept empty for the purpose of simply synchronization. Now along with this we will be using -delete option in rsync, which will delete all those files in the target directory, which are are not present in the source(in our case the source is an empty directory, so all the files in the destination directory will be deleted.)

Empty Directory: /home/blanktest

Directory to be emptied: /test

The results are pretty impressive, so its much better to use rsync if you want to empty a directory containing millions of files, compared to find command.

The below shown table summarizes the speed for file deletion in Linux, using different methods in Linux.

Источник

Читайте также:  Hdmi cable windows 10
Оцените статью