Linux delete file recursive

How to find and delete directory recursively on Linux or Unix-like system

Find command syntax to delete directory recursively

Try the find command:
find /dir/to/search/ -type d -name «dirName» -exec rm -rf <> +
Another option is as follows to recursively remove folders on Linux or Unix:
find /dir/to/search/ -type d -name «dirName» -exec rm -rf \;

Warning : Be careful with the rm command when using with find. You may end up deleting unwanted data.

Find will execute given command when it finds files or dirs. For example:
find . -type d -name «foo» -exec rm -rf <> +
OR
find . -type d -name «bar» -exec rm -rf «<>» \;
Sample outputs:

You can find directories that are at least four levels deep in the working directory /backups/:
find /backups/ -type d -name «bar» -depth +4 -print0 -exec rm -rf <> +

Finding and deleting directory recursively using xargs

The syntax is as follows to find and delete directories on Linux/Unix system. For example, delete all empty directories:
find /path/to/dir/ -type d -empty -print0 | xargs -0 -I <> /bin/rm -rf «<>»
In this example, remove all foo directories including sub-diretories in /backups/ folder:
find /backups/ -type d -name «foo*» -print0 | xargs -0 -I <> /bin/rm -rf «<>»
The second command is a secure version. It is fast too, and it deals with weird directory names with white spaces and special characters in it:

Hence, I would like readers to use the following syntax:
find /path/to/search/ -name «pattern» -print0 | xargs -0 -I <> /bin/rm -rf «<>»
Where find command options are:

  • -name «pattern» : Base of file name that matches shell pattern pattern. For example, foo, Foo*3 and so on.
  • -print0 : Show the full file name on the standard output, followed by a null character. This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs

And xargs command options are:

  • -0 : Input items given by find are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
  • -I <> : <> in the initial-arguments with names read from standard input. For example, dir names given by find command./li>
  • /bin/rm -rf «<>« : Run rm command that remove files or directories passed by <> .
Читайте также:  Nxcooking dll для windows 10

Shell script to recursively remove backups older than 30 days

Here is my sample script that removes older weekly backup of my VM tarballs stored in the following format:

Источник

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

Источник

Recursively delete all files with a given extension [duplicate]

I want to delete all *.o files in a directory and its sub-directories. However, I get an error:

On the other hand, rm *.o works, but it’s not recursive.

2 Answers 2

That is evil: rm -r is not for deleting files but for deleting directories. Luckily there are probably no directories matching *.o .

What you want is possible with zsh but not with sh or bash (new versions of bash can do this, but only if you enable the shell option globstar with shopt -s globstar ). The globbing pattern is **/*.o but that would not be limited to files, too (maybe zsh has tricks for the exclusion of non-files, too).

But this is rather for find :

or (as I am not sure whether -delete is POSIX)

That’s not quite how the -r switch of rm works:

rm has no file searching functionality, its -r switch does not make it descend into local directories and identify files matching the pattern you give it. Instead, the pattern ( *.o ) is expanded by the shell and rm will descend into and remove any directories whose name matches that pattern. If you had a directory whose name ended in .o , then the command you tried would have deleted it, but it won’t find .o files in subdirectories.

What you need to do is either use find :

or, for non-GNU find :

Alternatively, if you are using bash you can enable globstar :

NOTE: all three options will delete directories whose name ends in .o as well, if that’s not what you want, use one of these:

Источник

How to remove files and directories quickly via terminal (bash shell) [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 6 years ago .

From terminal window:

When I use the rm command it can only remove files.
When I use the rmdir command it only removes empty folders.

If I have a directory nested with files and folders within folders with files and so on, is there any way to delete all the files and folders without all the strenuous command typing?

If it makes a difference, I am using the mac bash shell from terminal, not Microsoft DOS or linux.

4 Answers 4

-r «recursive» -f «force» (suppress confirmation messages)

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

Yes, there is. The -r option tells rm to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir .

The other two options you should know are -i and -f . -i stands for interactive; it makes rm prompt you before deleting each and every file. -f stands for force; it goes ahead and deletes everything without asking. -i is safer, but -f is faster; only use it if you’re absolutely sure you’re deleting the right thing. You can specify these with -r or not; it’s an independent setting.

And as usual, you can combine switches: rm -r -i is just rm -ri , and rm -r -f is rm -rf .

Also note that what you’re learning applies to bash on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm ‘s syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.

Источник

How can I recursively delete all files of a specific extension in the current directory?

How do I safely delete all files with a specific extension (e.g. .bak ) from current directory and all subfolders using one command-line? Simply, I’m afraid to use rm since I used it wrong once and now I need advice.

8 Answers 8

You don’t even need to use rm in this case if you are afraid. Use find :

But use it with precaution. Run first:

to see exactly which files you will remove.

Also, make sure that -delete is the last argument in your command. If you put it before the -name *.bak argument , it will delete everything.

See man find and man rm for more info and see also this related question on SE:

First run the command shopt -s globstar . You can run that on the command line, and it’ll have effect only in that shell window. You can put it in your .bashrc , and then all newly started shells will pick it up. The effect of that command is to make **/ match files in the current directory and its subdirectories recursively (by default, **/ means the same thing as */ : only in the immediate subdirectories). Then:

(or gvfs-trash **/*.bak or what have you).

Deleting files is for me not something you should use rm for. Here is an alternative:

As Flimm states in the comments:

The package trash-cli does the same thing as gvfs-trash without the dependency on gvfs.

You don’t need to make an alias for this, because the trash-cli package provides a command trash , which does what we want.

As Eliah Kagan makes clear in extensive comments, you can also make this recursive using find . In that case you can’t use an alias, so the commands below assume you have installed trash-cli . I summarise Eliah’s comments:

This command finds and displays all .bak files and symlinks anywhere in the current directory or its subdirectories or below.

To delete them, append an -exec with the trash command:

-xtype f selects files and symlinks to files, but not folders. To delete .bak folders too, remove that part, and use -execdir , which avoids cannot trash non-existent errors for .bak files inside .bak directories:

Источник

Читайте также:  Linux terminal find all files
Оцените статью