- Use rm to Delete Files and Directories on Linux
- The Basics of Using rm to Delete a File
- Options Available for rm
- -i Interactive mode
- -f Force
- -v Verbose
- -d Directory
- -r Recursive
- Combine Options
- -rf Remove Files and Directories, Even if Not Empty
- Combine rm with Other Commands
- Remove Old Files Using find and rm
- How to Remove Files Recursively in Linux
- Deleting all files recursively in Linux
- How to remove files recursively by size
- How to remove files recursively by extension (File type)
- How to delete files recursively based on modification or creation time
- Conclusion
- About the author
- David Adams
- find’s «-exec rm <> \;» vs «-delete»
- 4 Answers 4
Use rm to Delete Files and Directories on Linux
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
This guide shows how to use rm to remove files, directories, and other content from the command line in Linux.
To avoid creating examples that might remove important files, this Quick Answer uses variations of filename.txt . Adjust each command as needed.
The Basics of Using rm to Delete a File
rm filename1.txt filename2.txt
Options Available for rm
-i Interactive mode
Confirm each file before delete:
-f Force
-v Verbose
Show report of each file removed:
-d Directory
Note: This option only works if the directory is empty. To remove non-empty directories and the files within them, use the r flag.
-r Recursive
Remove a directory and any contents within it:
Combine Options
Options can be combined. For example, to remove all .png files with a prompt before each deletion and a report following each:
remove filename01.png? y filename01.png remove filename02.png? y filename02.png remove filename03.png? y filename03.png remove filename04.png? y filename04.png remove filename05.png? y filename05.png
-rf Remove Files and Directories, Even if Not Empty
Add the f flag to a recursive rm command to skip all confirmation prompts:
Combine rm with Other Commands
Remove Old Files Using find and rm
Combine the find command’s -exec option with rm to find and remove all files older than 28 days old. The files that match are printed on the screen ( -print ):
find filename* -type f -mtime +28 -exec rm '<>' ';' -print
In this command’s syntax, <> is replaced by the find command with all files that it finds, and ; tells find that the command sequence invoked with the -exec option has ended. In particular, -print is an option for find , not the executed rm . <> and ; are both surrounded with single quote marks to protect them from interpretation by the shell.
This page was originally published on Tuesday, July 3, 2018.
How to Remove Files Recursively in Linux
After reading this article, you will be able to find and remove single or multiple files from the command line. This tutorial is optimized for both new and experienced Linux users.
The first section of this tutorial explains how to remove files recursively (directories with all their content and subdirectories’ content). Below I also added instructions to remove recursively certain types of files depending on their size, extension, creation or modification time, and permissions.
All practical examples in this document contain screenshots to make it easy for every Linux user to understand and apply them to their needs.
Deleting all files recursively in Linux
The first section shows how to use the rm (Remove) command to delete a directory with all its content, including all subdirectories with their files and additional subdirectories.
The rm command used with -r flag will remove all directories’ content independently of their type.
But first, let’s see the directories in my home using the ls command.
As you can see, I have 5 directories: Desktop, dir2, Documents, Downloads, and removerecurdir.
Let’s see the content of the directory named removerecurdir using the command tree as shown in the screenshot below.
According to the tree output the removerecurdir directory contains two directories that contain subdirectories and a file inside removecurdir: The directory dir1, with otherdir and otherdir2 subdirectories, and the directory dir2 contains a file named file3.
Let’s say we want to remove the removecurdir and all its content including all files and subdirectories. The proper command is the rm command followed by the -r flag as shown in the syntax below.
Thus, if I want to remove the removerecurdir with all the content, I run:
The subsequent ls output shows the directory, and all its content were successfully removed.
How to remove files recursively by size
This section shows how to recursively delete files smaller than 10 megabytes using the command find.
The syntax is the following:
Note that in the example below, I use sudo to get privileges to remove protected files.
The syntax to remove files greater than a specific size is very similar. The minus (-) symbol must be replaced by a plus symbol (+). The exact syntax is shown below.
In the example below I will use the previous syntax to remove files greater than 1 GB.
How to remove files recursively by extension (File type)
The current chapter explains how to delete files recursively by extension or file type.
On my home I have a directory named testhint. Let’s see its content using the tree command.
As you can see, the parent directory testhint contains a file (file1.txt) and two subdirectories: testhint2 containing file3.txt and the testhint3 subdirectory containing file3 and something.txt.
Let’s assume you want to recursively remove all txt files only. The syntax is the following:
Thus, to remove all txt files recursively within the parent directory testhint, I run the command shown in the figure below.
As you can see all txt files were removed, and only file3 without an extension remains.
You can also delete files by extension using find together with exec commands, as I will explain below.
Let’s see a new scenario with the same directory structure but different files.
The above image shows 4 log files and 3 files without extension.
The syntax to remove files by extensions using -exec is the following:
Thus, to remove the .log files from the previous screenshot, I ran the command below.
The image above shows all .log files were deleted while other files remained.
The xargs command offers the same solution. The difference between xargs and exec is that exec runs the rm function every time a file matches the condition. The command xargs executes the rm command once for all found files matching the condition.
The syntax to remove all files by extension with find and xargs is the following:
The new scenario depicted in the screenshot below shows five .c files in different subdirectories and five files without the .c extension.
To remove all .c files using xargs I run the command as shown below.
Again, you can see the selected extension files were successfully deleted.
Deleting all files recursively based on permissions
Let’s check the new content of the testhint directory.
There are four files with full permissions (file2, file3.c, file6.c and file7).
Now let’s assume you want to find and remove all files with full permissions for everyone.
The syntax is the following:
Thus, to remove all files with full access to all users, I execute the command below.
How to delete files recursively based on modification or creation time
The last section of this tutorial explains how to delete files recursively by creation or modification time.
The syntax is the following:
If you want to delete files created or modified in the last day (last 24 hours), run the following command, where 1 is the number of days, and the minus (-) symbol specifies files created or modified before the defined number of days.
To remove files created or modified before a day, before 24 hours, just replace the minus symbol for a plus symbol.
Conclusion
Since Linux is a very versatile and flexible operating system, users have different techniques to get the same result. All the alternatives explained above are valid for almost every Linux distribution. Some of the commands are even useful for some Unix systems. As you can see, implementing them is easy and any Linux user can do it independently of their knowledge level. To delete files recursively according to other conditions, check the main page of each command described in this article.
About the author
David Adams
David Adams is a System Admin and writer that is focused on open source technologies, security software, and computer systems.
find’s «-exec rm <> \;» vs «-delete»
I noticed that the -exec . <> method is preferred. Why? Which one is safer/faster/better? I’ve used both on my Macbook and everything appears to work well.
4 Answers 4
-delete will perform better because it doesn’t have to spawn an external process for each and every matched file, but make sure to call this option after the filtering criteria (i.e. -name , -cmin , -type , etc.), otherwise it will delete the specified entire file tree. Indeed, quoting the find manpage :
GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known
find . -name .DS_Store -type f -delete
It is possible that you may see -exec rm <> + often recommended because -delete does not exist in all versions of find . I can’t check right now but I’m pretty sure I’ve used a find without it.
Both methods should be «safe».
A common method for avoiding the overhead of spawning an external process for each matched file is:
find / -name .DS_Store -print0 | xargs -0 rm
(but note that there is a portability problem here too: not all versions of find have -print0 !)
I see. I’ve also read that using the -delete switch before -name deletes the specified file tree, so I guess I have to be careful.
.DS_Store doesn’t contain any special characters at all, so the quotes are unnecessary and change nothing in this case.
Basically only whitespace (spaces, tabs, maybe others) is the only thing that causes an unquoted string to be interpreted as two separate command line arguments, but that’s not all you have to sorry about when deciding whether or not to quote. You have to worry about all shell metacharacters like ; or | or > or < and `` and many others which have special meaning to the shell unless quoted.
@MarcoMarsala xargs takes care of the limited-size argument list problem transparently by breaking it up into multiple invocations of the command.
Assuming .DS_Store represent files and not directories, the most portable still fast way to do it would be:
sudo find / -name .DS_Store -exec rm <> +
The only risk is for sudo not to be available but it is quite low nowadays.
The -delete option used to demand FreeBSD or later GNU find and is still non standard in a few other find implementations, so is not always available.
The command termination + instead of \; highly optimizes the exec clause by not running the rm command for each and every .DS_Store present on the file system. It is more ubiquitous, being specified by POSIX.
-delete is from FreeBSD from 1996, not added to GNU find until 2004, -exec cmd <> + is from SysV in 80s, standardised by POSIX in 1992, added to GNU find in 2005.
For a machine such as your macbook you won’t find much difference in performance between the two commands. However, if you look at the -exec version you can see a subtle difference:
sudo find / -iname ".file-to-delete" -exec rm <> \;
This means that you will find all those files with name .file-to-delete . However this search might return some unwanted false positives. When doing something with sudo you should be a bit more careful. The advantage of using -exec rm <> is that you can pass arguments to rm like this:
sudo find / -iname "*~" -exec rm -i <> \;
In this example I want to remove those backup files that emacs makes. However that tilde could be in some obscure file that I don’t know about and could be important. Plus I want to confirm the delete. So I put the option -i on the rm command. This will give me an interactive delete.
Also you can refine the usage of rm to delete directories as well as files:
find /usr/local/share/ -iname "useless" -exec rm -r <> \;
In brief, the -exec gives you a bit more control over the actual command that removes the found item. The advantage is that you use one tool to find the files, another tool to remove them. Also not every version of the find utility has the -delete option. So better to use each tool for its proper job. This is the unix philosophy — one tool, one job, use them together to do what you need to do.