使用 rsync 只删除无关文件

Bry*_*yan 15 linux bash rsync

比较两个目录结构并删除目标位置中无关文件和目录的最佳方法是什么?

我有一个正在开发的小型网络照片库应用程序。用户使用 FTP 添加和删除图像。我编写的网络画廊软件会即时创建新的缩略图,但它不处理删除。我想要做的是安排一个命令/bash 脚本以预定义的时间间隔来处理这个问题。

原始图像/home/gallery/images/使用子目录存储并组织在相册中。缩略图缓存在 中/home/gallery/thumbs/,使用与图像目录相同的目录结构和文件名。

我尝试使用以下方法来实现这一点:

rsync  -r --delete --ignore-existing /home/gallery/images /home/gallery/thumbs
Run Code Online (Sandbox Code Playgroud)

如果所有缩略图都已被缓存,这会正常工作,但不能保证会是这种情况,当发生这种情况时,thumb 目录会将原始全尺寸图像复制到其中。

我怎样才能最好地实现我想要做的事情?

Jor*_*ril 39

你也需要--existing

rsync -r --delete --existing --ignore-existing /home/gallery/images /home/gallery/thumbs
Run Code Online (Sandbox Code Playgroud)

从联机帮助页:

  --existing, --ignore-non-existing
          This tells rsync to skip creating files (including  directories)
          that  do  not  exist  yet on the destination.  If this option is
          combined with the --ignore-existing option,  no  files  will  be
          updated  (which  can  be  useful if all you want to do is delete
          extraneous files).
Run Code Online (Sandbox Code Playgroud)

  • @LonnieBest 如果出现错误,即使是 `rm`、`cp` 或 `mv` 也不会起作用,因为这就是错误:它们是应该查看并阻止操作成功完成的问题。您可以指示大多数工具忽略错误(例如,`rm` 的`-f`),但我看不出这与问题或此答案有什么关系。 (2认同)

Tom*_*haw 8

我认为这不是rsync最好的方法。我会使用像下面这样的 bash one-liner:

$ cd /home/gallery/thumbs && find . -type f | while read file;do if [ ! -f "../images/$file" ];then echo "$file";fi;done
Run Code Online (Sandbox Code Playgroud)

如果此单行生成正确的文件列表,则您可以修改它以运行rm命令而不是echo命令。