tags:

views:

257

answers:

1

Example:

find / *

Gives me all files and directories, but I want only those files I may read and those directories I may see the contents of. Otherwise I get problems as when I try to find file information for all files:

for i in ls $( find / * ); do file $i; done

Which results in:

find: /lost+found: Permission denied
find: /proc/tty/driver: Permission denied
find: /proc/1/task/1/fd: Permission denied
find: /proc/1/fd: Permission denied
find: /proc/2/task/2/fd: Permission denied
find: /proc/2/fd: Permission denied
find: /proc/3/task/3/fd: Permission denied
# and so on ...

If it's possible I would like it in a generic way, so that I may use the same command line regardless of which user I am logged in as, but still get those files and directories I may see as a result from find.

+4  A: 

Use the -readable option to find (assuming a modern system using GNU findutils):

Matches files which are readable. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client’s kernel and so cannot make use of the UID mapping information held on the server.

Using -perm and variants doesn't work because it only looks at the file's flags, and not whether those flags give you access.

If you don't have -readable, you can pipe the output of find through this trivial Perl script which only outputs the file names of the supplied files that are readable:

#!/usr/bin/perl -w

use POSIX qw[access];
use strict;

foreach (split(/\0/, <STDIN>)) {
    print $_ . "\0" if (POSIX::access($_, &POSIX::R_OK));
}

e.g.

% find / -print0 | access_test | xargs -0 -n 1 do_cmd

but note that this will still generate output errors on stderr as find attempts to recurse into directories that it doesn't have permission for. The print0 option to find (and xargs -0) is there to make sure that the system works on file names with embedded spaces in them.

Alnitak
Thanks. Yes I did look at -perm before posting and it didn't seem to be for me. And it seems I'm not using a modern system, I'm using Fedora at the moment and -readable doesn't seem to work here.
DeletedAccount
It's present on my Fedora 10 system.
Alnitak
I've got Fedora release 7 (Moonshine) where I am (at the university) and I don't got admin rights. When I get home I've got Ubuntu 8.04 which I bet got it too. :-)
DeletedAccount
Actually no, it wasn't available by default in Ubuntu 8.04. But at home at least I can install it.
DeletedAccount