Real-Time Directory Sync on Linux

In this guide, we set up a system to mirror directory (`/home`) to another directory (`/srv/nfsroot/home`) in real-time. This is useful for clusters, multi-node setups, or ensuring your data is always backed up.


1. Install Required Packages

We need inotify-tools to monitor file changes and rsync to efficiently sync files. Both are free and open-source.

sudo pacman -S inotify-tools rsync

2. Create the Sync Script

Create a script that watches your home folder and syncs any changes:

sudo vim /usr/local/bin/homesync.sh

Paste the following:

#!/bin/bash
SRC="/home/"
DST="/srv/nfsroot/home/"

mkdir -p "$DST"

# Infinite watch loop
while inotifywait -r -e modify,create,delete,move "$SRC"; do
    rsync -a --delete "$SRC" "$DST"
done

Ensure that both directories exist.

Make it executable:

sudo chmod +x /usr/local/bin/homesync.sh

3. Create a systemd Service

Run the sync script as a background service that starts on boot:

sudo vim /etc/systemd/system/homesync.service

Paste this configuration:

[Unit]
Description=Real-time local /home sync

[Service]
ExecStart=/usr/local/bin/homesync.sh
Restart=always
User=root

[Install]
WantedBy=multi-user.target

4. Enable and Start the Service

sudo systemctl daemon-reload
sudo systemctl enable homesync.service
sudo systemctl start homesync.service

5. Verify the Service

Check if it’s running:

systemctl status homesync.service

It should show active (running). Any changes in /home will now automatically mirror to /srv/nfsroot/home.