我正在收集一个目录下的所有文件。但是该目录具有指向我运行 find 命令的目录之外的其他目录的符号链接,并且它包含大量文件和目录。虽然我可以在 prune 的帮助下忽略这个目录,但当符号链接指向这个大目录的子目录时,就会出现问题。我想忽略指向子目录上任何符号链接的所有符号链接。
这是一个示例命令find -L /usr/local/searchdir
很少的符号链接
/usr/local/searchdir/d0/link --> /small/dir
/usr/local/searchdir/d1/file.o
/usr/local/searchdir/d2/link --> /little/dir
/usr/local/searchdir/d3/link --> /hugedir
/usr/local/searchdir/d4/link --> /hugedir/main
.
.
.
/usr/local/searchdir/dx --> /hugedir/c4
有问题的目录
/hugedir/c1/tmp
/hugedir/c2/main
/hugedir/c3/dir
/hugedir/c4/ext
/hugedir/c5/client
/hugedir/c6/bin
/hugedir/c7/std
答案1
GNUfind
有一个-lname
选项来匹配符号链接的目标,但它不能与-L
/一起使用-follow
。
假设您确实想使用-L
,您需要调用-exec
来实现您自己的检查,以确保链接位于该大目录上。
这里使用 GNUfind
作为-xtype
优化,假设您的系统有readlink
并且支持-f
GNU 选项readlink
:
find -L . -type d -xtype l -exec sh -c '
case $(readlink -f "$1") in
(/hugedir | /hugedir/*) exit 0;;
(*) exit 1;;
esac' sh {} \; -prune -o ...
或者效率稍微高一点。
find -L . -type d -xtype l -exec sh -c '
cd -P "$1" && case $PWD in
(/hugedir | /hugedir/*) exit 0;;
(*) exit 1;;
esac' sh {} \; -prune -o ...
答案2
默认情况下,该find
命令会忽略符号链接。无论如何,您可以通过标志明确指定此行为-P
:
-P Never follow symbolic links. This is the default behaviour. When find examines or prints information a file, and the file is a symbolic link, the information used shall be taken from the
properties of the symbolic link itself.
-L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link
itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will
still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched.
When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is
broken). Using -L causes the -lname and -ilname predicates always to return false.
-H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the proper‐
ties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation,
the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the sym‐
bolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined
(though of course -maxdepth 0 would prevent this).