I'm using find
to delete files matching some criteria:
find -type f [more criteria] -delete
That works fine, in general, but I'm running into issues with sub-directories created by other users: as far as I understand, whether I'm allowed to delete a file depends on my permissions w.r.t. the parent directory. Hence the command above fails for files contained in a sub-directory created by another user:
fbrucker@host /tmp $ ls -lh
total 4,0K
drwxrwxr-x 2 root root 4,0K Jun 15 11:44 foo/
fbrucker@host /tmp $ ls -lh foo/
total 0
-rw-rw-r-- 1 fbrucker fbrucker 0 Jun 15 11:44 a
-rw-rw-r-- 1 root root 0 Jun 15 11:44 b
fbrucker@host /tmp $ find -type f -delete
find: cannot delete ‘./foo/b’: Permission denied
find: cannot delete ‘./foo/a’: Permission denied
It's OK that I cannot delete the files, but the missing permissions make find
exit with a non-zero status. I'd like to avoid that.
How can I filter out files that I cannot delete before trying to delete them?
Note that simply filtering out the error messages is not enough for me, since that will still leave me with the non-zero exit code. Also, ignoring the exit code completely won't work for me, because I do want catch other errors (my real find
command is more complex, for example for find /somedir -type f -delete
I'd like to not ignore the error that is raised when /somedir
does not exist).
I know that find
has tests for the file's permissions (e.g. -perm
, -readable
, -writable
), but I don't think they apply here. For example,
fbrucker@host /tmp $ find -type f -writable
./foo/a
even though I cannot delete foo/a
since I don't have the necessary permissions on foo
.
What I'm looking for is something like a -deletable
test, which doesn't seem to exist.
-deletable
is the classic "time of check to time of use" issue. The permissions of a file might change in the middle, so that-deletable
would be truthy, and the deletion would still fail. It's better to just try to do it and deal with or ignore the error later.