在 macOS 上使用“find ... -delete”出现“相对路径可能不安全”错误

Bar*_*urg 6 osx find

我正在尝试删除包含特定文本的所有文件,如下所示:

$ find ~/Library/MobileDevice/Provisioning\ Profiles/* -exec grep -l "text to search for" '{}' \; -delete
/Users/build/Library/MobileDevice/Provisioning Profiles/06060826-3fb2-4d71-82c6-7b9d309b08d6.mobileprovision
find: -delete: /Users/build/Library/MobileDevice/Provisioning Profiles/06060826-3fb2-4d71-82c6-7b9d309b08d6.mobileprovision: relative path potentially not safe
Run Code Online (Sandbox Code Playgroud)

但是,如您所见,它会发出警告,然后不会删除该文件。我该如何解决这个错误?

这是在 Mac 上。

Sté*_*las 14

macOSfind基于旧版本的 FreeBSD,find-delete不会删除作为参数给出的文件。

当你这样做时:

find dir/* ... -delete
Run Code Online (Sandbox Code Playgroud)

您的shell正在将该dir/*glob扩展为文件路径列表(不包括隐藏的路径,而find它本身不会排除它在任何这些目录中找到的隐藏文件),因此find接收如下内容:

find dir/dir1 dir/dir2 dir/file1 dir/file2... ... -delete
Run Code Online (Sandbox Code Playgroud)

如果dir/file1匹配 macOSfind-delete将拒绝删除它。dir/dir1/.somefile如果匹配,它会很高兴地删除 a 。

在 2013 年的 FreeBSD 中发生了变化,但这种变化显然没有适用于 macOS。在这里,解决方法很简单:使用find dir(或者,find dir/如果您想允许作为dir指向目录的符号链接并find进入该目录)而不是find dir/*. 所以,在你的情况下:

find ~/Library/MobileDevice/Provisioning\ Profiles/ \
  -exec grep -l "text to search for" '{}' \; -delete
Run Code Online (Sandbox Code Playgroud)

或者使用更有效的grep -l --null | xargs -0方法


rco*_*oup 6

我在 macOS 上遇到了这个问题,从目录树中删除了档案之外的所有内容:

find top ! -name "*.tar.gz" -print -delete
... snip ...
top
find: -delete: top: relative path potentially not safe
Run Code Online (Sandbox Code Playgroud)

解决方案是添加-mindepth 1以排除顶级目录

find top/path -mindepth 1 ! -name "*.tar.gz" -print -delete
Run Code Online (Sandbox Code Playgroud)