同步文件的最佳方式 - 仅复制现有文件,并且仅在比目标更新时复制

Mou*_*inX 25 backup rsync file-copy synchronization

我正在 Ubuntu 12.04 上进行本地同步。这些文件通常是小的文本文件(代码)。

我想从复制(保留修改时间标记)source目录target,但我只想要复制如果文件target 已经存在,而且是较旧的一个比source

所以我只复制较新的文件source,但它们必须存在,target否则不会被复制。(source将有比target.多得多的文件。)

我实际上将从source多个target目录复制。我会提到这一点,以防它影响解决方案的选择。但是,如果需要,我可以轻松地多次运行我的命令,target每次都指定新的。

slm*_*slm 36

我相信你可以rsync用来做到这一点。关键的观察是需要使用--existing--update开关。

        --existing              skip creating new files on receiver
        -u, --update            skip files that are newer on the receiver
Run Code Online (Sandbox Code Playgroud)

像这样的命令可以做到:

$ rsync -avz --update --existing src/ dst
Run Code Online (Sandbox Code Playgroud)

例子

假设我们有以下示例数据。

$ mkdir -p src/; touch src/file{1..3}
$ mkdir -p dst/; touch dst/file{2..3}
$ touch -d 20120101 src/file2
Run Code Online (Sandbox Code Playgroud)

如下所示:

$ ls -l src/ dst/
dst/:
total 0
-rw-rw-r--. 1 saml saml 0 Feb 27 01:00 file2
-rw-rw-r--. 1 saml saml 0 Feb 27 01:00 file3

src/:
total 0
-rw-rw-r--. 1 saml saml 0 Feb 27 01:00 file1
-rw-rw-r--. 1 saml saml 0 Jan  1  2012 file2
-rw-rw-r--. 1 saml saml 0 Feb 27 01:00 file3
Run Code Online (Sandbox Code Playgroud)

现在,如果我要同步这些目录,什么都不会发生:

$ rsync -avz --update --existing src/ dst
sending incremental file list

sent 12 bytes  received 31 bytes  406.00 bytes/sec
total size is 0  speedup is 0.00
Run Code Online (Sandbox Code Playgroud)

如果我们touch有一个源文件使它更新:

$ touch src/file3 
$ ls -l src/file3
-rw-rw-r--. 1 saml saml 0 Feb 27 01:04 src/file3
Run Code Online (Sandbox Code Playgroud)

rsync命令的另一次运行:

$ rsync -avz --update --existing src/ dst
sending incremental file list
file3

sent 115 bytes  received 31 bytes  292.00 bytes/sec
total size is 0  speedup is 0.00
Run Code Online (Sandbox Code Playgroud)

我们可以看到file3,因为它是新的,并且它存在于 中dst/,所以它会被发送。

测试

为了在切断命令之前确保一切正常,我建议使用 的另一个rsync开关,--dry-run。让我们也添加另一个,-v以便rsync输出更详细。

$ rsync -avvz --dry-run --update --existing src/ dst 
sending incremental file list
delta-transmission disabled for local transfer or --whole-file
file1
file2 is uptodate
file3 is newer
total: matches=0  hash_hits=0  false_alarms=0 data=0

sent 88 bytes  received 21 bytes  218.00 bytes/sec
total size is 0  speedup is 0.00 (DRY RUN)
Run Code Online (Sandbox Code Playgroud)