问题
I have a very specific need to find unowned files and directories in Solaris using a script, and need to be able to exclude full directory paths from the find because they contain potentially thousands of unowned files (and it's normal because they are files hosted on other servers). I don't even want find to search in those directories as it will hang the server (cpu spiking to 99% for a long time), therefore piping the find results in egrep to filter out those directories is not an option.
I know I can do this to exclude one of more directories by name:
find / -mount -local \( -type d -a \( -name dir1 -o -name dir2 -o dir3 \) \) -prune -o \( -nouser -o -nogroup \) -print
However, this will match dir1 and dir2 anywhere in the directory structure of any directories, which is not what I want at all.
I want to be able to prevent find from even searching in the following directories (as an example):
/opt/dir1
/opt/dir2
/var/dir3/dir4
And I still want it to find unowned files and directories in the following directories:
/opt/somedir/dir1
/var/dir2
/home/user1/dir1
I have tried using regex in the -name arguments, but since find only matches 'name' against the basename of what it finds, I can't specify a path. Unfortunately, Solaris's find does not support GNU find options such as -wholename or -path, so I'm kind of screwed.
My goal would be to have a script with the following syntax:
script.sh "/path/to/dir1,/path/to/dir2,/path/to/dir3"
How could I do that using find and standard sh scripting (/bin/sh) on Solaris (5.8 and up)?
回答1:
You can't match files by full path with Solaris find, but you can match files by inode. So use ls -i
to generate a list of inodes to prune, then call find
. This assumes that there aren't so many directories you want to prune that you'd go over the command line length limit.
inode_matches=$(ls -bdi /opt/dir1 /opt/dir2 /var/dir3/dir4 |
sed -e 's/ *\([0-9][0-9]*\) .*/-inum \1 -o/')
find / -xdev \( $inode_matches -nouser -o -nogroup \) -prune -o -print
An alternative approach would be to use a Perl or Python script and roll your own directory traversal. Perl ships with a find2perl
script that can get you started with the File::Find
module. In Python, see the walk
function in the os.path
module.
来源:https://stackoverflow.com/questions/7854975/how-to-exclude-a-list-of-full-directory-paths-in-find-command-on-solaris