Aashish P
Aashish P

Reputation: 1956

Difference between 'find -delete' and 'rm -rf'?

I want to delete files from a specific directory recursively. So, I have used

find . -wholename "*.txt" -delete

We can also delete the files using

rm -rf *.txt

What is the difference between deletion of file using rm and find ??

Upvotes: 13

Views: 22893

Answers (3)

reinierpost
reinierpost

Reputation: 8591

find . -name abd.txt -delete tries to remove all files named abd.txt that are somewhere in the directory tree of .

find . -wholename abd.txt -delete tries to remove all files with a full pathname of abd.txt somewhere in the directory tree of .

No such files will ever exist: when using find ., all full pathnames of files found will start with ./, so even a file in the current directory named abd.txt will have path ./abd.txt, and it will not match.

find . -wholename ./abd.txt -delete will remove the file in the current directory named abd.txt.

find -wholename ./abd.txt -delete will do the same.

The removal will fail if abd.txt is a nonempty directory.

(I just tried the above with GNU find 4.6.0; other versions may behave differently.)

rm -rf abd.txt also tries to remove abd.txt in the current directory, and if it is a nonempty directory, it will remove it, and everything in it.

To do this with find, you might use

find . -depth \( -wholename ./abd.txt -o -wholename ./abd.txt/\* \) -delete

Upvotes: 9

Mav55
Mav55

Reputation: 4280

find used with -delete, finds the files and deletes them. Find command takes in the path to look for the files and then the -delete flag deletes the files found in that given path. So, you can say find is more of a selective delete

Whereas rm -rf command deletes files/directories recursively no matter what. It means rm will delete all the files and directories at the specific path. -r stands for recursion and -f is force delete. So, rm coupled with -rf will keep on deleting the directories and files within directories at the target path until it finds no more.

Upvotes: 2

Jo So
Jo So

Reputation: 26501

While find -wholename GLOBPATTERN tries to match every file below the current directory (independent of the depth), the glob you used with the rm command is only matched against files which are directly (depth 1) under the current directory.

Btw. you don't need the -r switch to rm unless you want to recursively delete a directory (Because of the .txt extension, I assume you only want to delete regular files)

Upvotes: 3

Related Questions