Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ??

like image 970
Aashish P Avatar asked Jul 02 '12 10:07

Aashish P


2 Answers

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

like image 179
reinierpost Avatar answered Oct 20 '22 04:10

reinierpost


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)

like image 40
Jo So Avatar answered Oct 20 '22 06:10

Jo So