[TriLUG] `find -delete` not deleting
Ed Blackman via TriLUG
trilug at trilug.org
Tue Sep 27 14:28:49 EDT 2016
On Tue, Sep 06, 2016 at 04:11:54PM +0000, Joseph Mack NA3T via TriLUG wrote:
> I store photos every 5 mins from my house webcams. After a week, I scrub
> them with the following crontab entry.
>
> 32 0 * * * find $top_dir -mtime +7 -delete > /dev/null 2>&1
[...]
> What seems to have happening is that while the delete was running, it
> changed the date of the directory from a week ago, to the date of the
> cronjob. The directory (here 20160827) then is not old any more and is not
> deleted till a week later.
>
> I can't figure out if maxdepth or mindepth will fix my problem.
Sorry for the late reply, but none of the other replies showed the
minimal change that I think will fix the problem:
find $top_dir -depth -mtime +7 -delete > /dev/null 2>&1
find normally operates on objects as it finds them. That's usually
fine, but fails when removing directory trees. That's because -delete
will not remove a directory if it's not empty. Therefore, you need to
have find go all the way out to the furthest leaves (files or empty
directory), delete them, and then move up to their parents. -depth is
the option you need to tell find to do that.
$ mkdir -p /tmp/test/{1,2}; touch -m -d 'now -8 days' /tmp/test/{1,2}{/{a,b},}
$ find /tmp/test/ -mtime +7 # note that root directories come first
/tmp/test/2
/tmp/test/2/a
/tmp/test/2/b
/tmp/test/1
/tmp/test/1/a
/tmp/test/1/b
$ find /tmp/test/ -depth -mtime +7 # note that leaves come first
/tmp/test/2/a
/tmp/test/2/b
/tmp/test/2
/tmp/test/1/a
/tmp/test/1/b
/tmp/test/1
$ find /tmp/test/ -depth -mtime +7 -delete
$ ls /tmp/test/
$
-depth is specified in POSIX. In my version of GNU find, the man page
says that -delete implicitly turns on the -depth option, but -delete
isn't POSIX, so I'm guessing that your find doesn't do that.
If that's not it, I'd suggest temporarily redirecting the output
somewhere other than /dev/null and see if find is complaining about
anything.
--
Ed Blackman
More information about the TriLUG
mailing list