Automate Linux File Sync with inotify and rsync
Learn how to use Linux's inotify-tools to monitor directory changes and automatically synchronize modified files with rsync, covering installation, command options, example output, an event‑handling shell script, and running the script in the background with nohup.
Overview
This guide shows how to combine inotify-tools and rsync to automatically sync files when a directory changes on Linux. It is useful for continuous deployment or keeping backup copies up to date.
Installing inotify-tools
On a system with yum, install the utilities with: yum install inotify-tools The package provides two commands: inotifywait (used for waiting on events) and inotifywatch (for statistics). The tutorial focuses on inotifywait.
Monitoring command and options
To watch a directory (e.g., /usr/local/src) continuously and output concise event information, run:
/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w %f %e' -e modify,delete,create,attrib /usr/local/srcKey options: -m: keep listening after the first event -r: watch directories recursively -q: suppress non‑essential messages -e: specify which events to monitor (modify, delete, create, attrib) --timefmt: format for the timestamp, e.g.,
'%d/%m/%y %H:%M' --format: customize output using placeholders: %T – time according to
--timefmt %w– directory where the event occurred %f – file name %e – event type
Example output
Creating a file 1.txt in the watched directory produces:
22/03/18 17:22 /usr/local/src/ 1.txt CREATE
22/03/18 17:22 /usr/local/src/ 1.txt ATTRIBShell script for handling events
The following script loops on events and runs a user‑specified script whenever a file is created, modified, or deleted:
#!/bin/sh
# Monitored file or directory
filename=$1
# Script to execute on change
script=$2
inotifywait -mrq --format '%e' --event create,delete,modify $filename | while read event
do
case $event in
MODIFY|CREATE|DELETE) bash $script ;;
esac
doneRunning the script in the background
Use nohup to detach the script from the terminal and redirect output: nohup sh test.sh > out.txt & This setup enables continuous, automated file synchronization without manual intervention.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
