shell脚本实现文件同步

文件同步

实现功能

有两个文件夹A,B我需要持续监控A的数据增量(数据包含文件夹)然后拷贝到B中去(保持和A中目录结构一样),然后我删除B中的数据,A中的数据不变,B只能拷贝每次的增量文件

前置条件

##########需要安装inotify-tools包###########
#yum install inotify-tools -y
##########################################

代码部分

#!/bin/bash
# 设置文件夹A和B的路径
DIR_A="/root/A"
DIR_B="/root/B"

rsync -avzh --update --delete "$DIR_A/" "$DIR_B/"

inotifywait -m -r -e create,move,modify,delete "$DIR_A" | while read -r directory events filename; do
  if [ -d "$directory/$filename" ]; then
    mkdir -p "$DIR_B/${directory#$DIR_A}/$filename"
  else
    rsync -avzh --update "$directory/$filename" "$DIR_B/${directory#$DIR_A}/"
  fi
done