在 Ubuntu 中同步多个文件夹的常用做法
一、使用 rsync 并行同步多个目录
rsync -avz /src/dir1/ /dst/dir1/ &
rsync -avz /src/dir2/ /dst/dir2/ &
rsync -avz /src/dir3/ /dst/dir3/ &
wait
sudo apt-get install -y parallel
find /src -mindepth 1 -maxdepth 1 -type d > dir_list.txt
cat dir_list.txt | parallel -j 4 rsync -avz {} /dst/{/}
rsync -avz -e 'ssh -p 2222' /src/dir1/ user@host:/dst/dir1/
二、使用 inotifywait + rsync 实现近实时同步
sudo apt-get install -y rsync inotify-tools
用 inotifywait 监听 create、modify、delete、move 等事件,触发 rsync 同步对应目录。#!/usr/bin/env bash
SRC="/data"
DST="user@host:/backup/data"
RSYNC_OPTS="-avz --delete -e ssh"
inotifywait -m -r -e modify,create,delete,move --format '%w%f' "$SRC" | while IFS= read -r file; do
echo "$(date '+%F %T') change detected: $file, syncing..."
rsync $RSYNC_OPTS "$SRC/" "$DST/"
done
建议将脚本加入系统服务并设置开机自启,确保持续运行与日志留存。三、使用 Syncthing 在多台设备间持续同步多个文件夹
sudo apt-get install -y syncthing
# 启动一次以生成配置,然后按需在桌面环境使用 systemd 管理
systemctl --user enable --now syncthing.service # 或 systemctl enable --now syncthing@$USER.service
四、图形化工具 FreeFileSync 批量同步
五、方法对比与选型建议
| 方案 | 实时性 | 传输方式 | 易用性 | 典型场景 |
|---|---|---|---|---|
| rsync 并行 | 非实时(可配合定时) | 本地/SSH | 中 | 批量同步、脚本化、可控性强 |
| inotify+rsync | 近实时 | 本地/SSH | 中-高 | 频繁变更目录的自动同步 |
| Syncthing | 持续近实时 | P2P 直连 | 高 | 多设备持续同步、跨平台 |
| FreeFileSync | 手动/计划任务 | 本地/网络/SSH | 高 | 可视化对比与配置、一次性/定期批量 |