@[TOC]unison与fswatch文件同步
官网: https://www.cis.upenn.edu/~bcpierce/unison/
Unison 是双向同步的,一个缺点是,对于一个文件在两个同步文件夹中都被修改时,unison是不会去同步的,因为unison无法判断以那个为准.
brew install unison
apt-get -y install unison
"unison.exe" unison -version
unison -batch /data ssh://root@127.0.0.1:2222//data
配置文件一定是在 unison 指定的配置目录,每个系统路径不同,
unison [随便文件名] 会报错,但是也会提示具体的配置文件目录
即看到命配置文件为 /Users/modongxiao/Library/Application Support/Unison/aaaaaa.prf
bogon:~ modongxiao$ unison aaaaaa
Usage: unison [options]
or unison root1 root2 [options]
or unison profilename [options]
For a list of options, type "unison -help".
For a tutorial on basic usage, type "unison -doc tutorial".
For other documentation, type "unison -doc topics".
To start interactive profile selection, type "unison -i".
Profile /Users/modongxiao/Library/Application Support/Unison/aaaaaa.prf does not exist
# 要同步的文件夹
root = /data
#要同步的文件夹
root = ssh://root@127.0.0.1:2222//data
# 全自动模式,接受并执行默认动作
batch = true
#同步时最大线程数
maxthreads = 3000
#间隔一秒后,开始新一次同步检查
repeat = 2
#重试次数
retry = 1
#使用ssh压缩传输方式
sshargs = -C
unison data
bogon:docker modongxiao$ unison data
Unison 2.51.4 (ocaml 4.12.0): Contacting server...
Connected [//4554e2191dd9//data -> //bogon//Users/modongxiao/data]
Looking for changes
Waiting for changes from server
Reconciling changes
new file <-?-> new file .DS_Store
local : new file modified on 2021-12-17 at 20:56:53 size 6148 rw-r--r--
No updates to propagate
Synchronization complete at 21:38:39 (0 items transferred, 18 skipped, 0 failed)
skipped: .DS_Store (contents changed on both sides)
skipped: app/.DS_Store (contents changed on both sides)
skipped: app/learnapi/.DS_Store (contents changed on both sides)
Sleeping for 2 seconds...
出现 skipped 就是冲突的文件
unison -force=/data -batch /data ssh://root@127.0.0.1:2222//data
fswatch 一个文件修改监视器,当指定的文件或者文件夹被修改的时候会受到通知。
# mac 系统
brew install fswatch
# debian 等系统
apt-get install fswatch
# centos 等系统
yum -y install fswatch
vi fswatch.sh
fswatch /data -o -l 1 | while read file
do
unison -batch /data ssh://root@127.0.0.1:2222//data
done
# 可以监控多个文件变化
# fswatch /data /mvc /abc /def /tmp | while read file
#/bin/bash
# log目录
LOG_DIR="/tmp/unison.log"
# 本机目录
LOCAL_DIR="/data"
# 远程地址
DIST_DIR="ssh://root@127.0.0.1:2222//data"
# 初始同步 以本地目录为主同步
unison -force=${LOCAL_DIR} -batch ${LOCAL_DIR} ${DIST_DIR}
fswatch ${LOCAL_DIR} -o | while read file; do
# 清空log文件
echo '' >$LOG_DIR
# 文件同步
unison -batch ${LOCAL_DIR} ${DIST_DIR} -silent -logfile ${LOG_DIR}
# 打印日志
cat $LOG_DIR
# 判断是否有冲突文件 cat 文件 | 匹配最后一行 | 去除前面开始的空格 | 匹配以skipped开头
cat /mvc/unison.log | awk 'END {print}' | awk '{sub("^ *","");sub(" *$","");print}' | grep "^skipped"
# 匹配成功
if [ $? == 0 ]; then
unison -force=${LOCAL_DIR} -batch ${LOCAL_DIR} ${DIST_DIR}
echo "文件冲突,以本地文件为主";
fi
done
# 可以监控多个文件变化
# fswatch /data /mvc | while read file
# -l 1 延迟1秒
#fswatch /data -o -l 1 | while read file