Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ever try to delete files with unix shell find? Use the -delete option

This has come up a number of times in posts, so I'm mentioning it as a thankyou to all helpful people on stackoverflow.

Have you ever wanted to do a bunch of deletes from the command line/terminal in Unix? Perhaps you used a construct like

find . -name '*.pyc' -exec rm {} \;

Look to the answer for an elegant way to do this.

like image 616
kd4ttc Avatar asked Jun 06 '12 22:06

kd4ttc


2 Answers

Here's how to do it with the -delete option!

Use the find command option -delete:

find . -name '*.pyc' -delete

Of course, do try a dry run without the -delete, to see if you are going to delete what you want!!! Those computers do run so darn fast! ;-)

like image 135
kd4ttc Avatar answered Oct 22 '22 14:10

kd4ttc


+1 for taking the initiative and finding the solution to your issue yourself. A couple of rather minor notes:

I would recommend getting into the habit of using the -type f flag when you're wanting to delete files. This restricts find to files that are actually files (i.e. not directories or links). Otherwise you might inadvertently delete a directory, which is probably not what you wanted to do. (That said, unless you have a directory named 'something.pyc', that wouldn't be an issue for your example command. It's just a good habit in general.)

Also, just to let you know, if you decide use the -exec rm.. version, it would run faster if you did this instead:

find . -type f -name '*.pyc' -exec rm {} \+

This version adds as many arguments to a single invokation of rm as it can, thereby reducing the total number of calls to rm. It works pretty much like the default behavior in xargs.

like image 34
Tim Pote Avatar answered Oct 22 '22 13:10

Tim Pote