Über das Paket inotifywait können Änderungen an kompletten Verzeichnisbäumen überwacht werden.

inotify-tools is a set of command-line programs for Linux providing a
simple interface to inotify. These programs can be used to monitor and
act upon filesystem events. inotify-tools consists of two utilities:

inotifywait simply blocks for inotify events, making it appropriate
for use in shell scripts.

inotifywatch collects filesystem usage statistics and outputs counts
of each inotify event.

Das Paket installieren wir mit folgendem Kommando:

apt install inotify-tools

Wir nutzen nun inotifywait in einem Script, um eine Dateistruktur zu überwachen. Das Tool ist eine dauerhaft laufende, blockierende Konsolenanwendung. Über eine While-Schleife fragen wir den Status ab und reagieren auf die Events modify,delete und create. In dem Beispielscript wird eine Mail als Info gesendet. Man kann natürlich auch in eine Textdatei loggen oder was auch immer.

#!/bin/bash

mail_info () {
        RECIPIENTS="some@domain.de"
        FROM="me@domain.de"
        echo "$2" | mail --content-type 'text/plain; charset=utf-8' -aFrom:"$FROM" -s "$1" "$RECIPIENTS"
}

file_removed() {
        TIMESTAMP=`date`
        SUBJECT="Datei gelöscht"
        BODY="[$TIMESTAMP]: $2 wurde von $1 gelöscht"
        mail_info "$SUBJECT" "$BODY"
}

file_modified() {
        TIMESTAMP=`date`
        SUBJECT="Datei geändert"
        BODY="[$TIMESTAMP]: Die Datei $1$2 wurde geändert"
        mail_info "$SUBJECT" "$BODY"
}

file_created() {
        TIMESTAMP=`date`
        SUBJECT="Datei geändert"
        BODY="[$TIMESTAMP]: Die Datei $1$2 wurde erstellt"
        mail_info "$SUBJECT" "$BODY"
}

inotifywait -q -m -r -e modify,delete,create $1 | while read DIRECTORY EVENT FILE; do
    case $EVENT in
        MODIFY*)
            file_modified "$DIRECTORY" "$FILE"
            ;;
        CREATE*)
            file_created "$DIRECTORY" "$FILE"
            ;;
        DELETE*)
            file_removed "$DIRECTORY" "$FILE"
            ;;
    esac
done

Das Script erhält als Parameter das zu überwachende Verzeichnis und muss als Hintergrundprozess ausgeführt werden, z.B. so:

monitor_directory_tree.sh /directory/name &