0%

rsync自动同步文件

目标

当A上的/your/source/dir内的文件发生改动时,自动从A上的/your/source/dir同步修改到B的/your/destination/dir

一. 安装inotify-tools用于检测文件变动

1
sudo apt-get install inotify-tools

二. 同步脚本

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/sh
#
# rsync.sh
#

SRC=/your/source/dir
DST=username@host:/your/destination/dir

inotifywait -mrq --exclude '.git*' -e modify,delete,create,move ${SRC} | while read DIR EVENT FILE
do
/usr/bin/rsync -ahqzt --delete $SRC $DST
done

脚本解释

1 事件监听:

1
inotifywait -mrq --exclude '.git*' -e modify,delete,create,move ${SRC}

-m 保持监听,否则执行一次后退出
-r 递归监听
-q 只输出事件
--exclude '.git*' 不监听.git开头的文件
-e modify,delete,create,move 监听修改,删除,创建,移动事件

所有支持的事件如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Events:
access file or directory contents were read
modify file or directory contents were written
attrib file or directory attributes changed
close_write file or directory closed, after being opened in
writable mode
close_nowrite file or directory closed, after being opened in
read-only mode
close file or directory closed, regardless of read/write mode
open file or directory opened
moved_to file or directory moved to watched directory
moved_from file or directory moved from watched directory
move file or directory moved to or from watched directory
create file or directory created within watched directory
delete file or directory deleted within watched directory
delete_self file or directory was deleted
unmount file system containing file or directory unmounted

该命令会返回3个值,分别为目录、事件、文件

2 同步

1
rsync -ahqzt --delete $SRC $DST

-a 归档模式
-h 适合阅读
-q 抑制非错误信息
-z 压缩传输
-t 保存修改事件
--delete 删除目标文件夹中多余的文件

三. 自动启动

/etc/rc.local 添加

1
su - user -c '/path/rsync.sh' >> '/path/rsync.log' &