Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mdutt247/2fbb1481a84b4522e31a9255215fbdaf to your computer and use it in GitHub Desktop.
Save mdutt247/2fbb1481a84b4522e31a9255215fbdaf to your computer and use it in GitHub Desktop.
To send an email notification whenever a file or directory changes in multiple watch directories while excluding certain subdirectories,
you can use inotifywait (from inotify-tools) along with mail or sendmail.
sudo apt update
sudo apt install inotify-tools mailutils -y
Here
inotify-tools: Monitors filesystem changes.
mailutils: Enables email sending (for mail command).
sudo nano /usr/local/bin/watch_changes.sh
#!/bin/bash
# Set email recipient
EMAIL="[email protected]"
# Log file
LOG_FILE="/var/log/inotify_changes.log"
# Directories to monitor (separated by space)
WATCH_DIRS=("/etc" "/root" "/home" "/var/www")
# Excluded directories (patterns matched within WATCH_DIRS)
EXCLUDE_PATTERNS=("node_modules" "cache" "logs")
# Convert exclude patterns into grep format
EXCLUDE_REGEX=$(printf "|%s" "${EXCLUDE_PATTERNS[@]}")
EXCLUDE_REGEX=${EXCLUDE_REGEX:1} # Remove leading "|"
# Monitor changes
inotifywait -m -r -e modify,create,delete,move --format '%w%f %e' "${WATCH_DIRS[@]}" |
while read FILE EVENT; do
# Skip excluded directories
if [[ "$FILE" =~ $EXCLUDE_REGEX ]]; then
continue
fi
# Log event
echo "$EVENT" | tee -a "$LOG_FILE"
# Send email notification
echo "Change detected:\n$EVENT" | mail -s "File Change Alert" "$EMAIL"
done
Make the Script Executable.
sudo chmod +x /usr/local/bin/watch_changes.sh
Run the script in the background so it continuously monitors file changes.
nohup /usr/local/bin/watch_changes.sh >/dev/null 2>&1 &
To stop it, find the process
ps aux | grep watch_changes.sh
Then kill it
kill <PID>
#To start the script on system boot, add it to cron
#sudo crontab -e
#@reboot nohup /usr/local/bin/watch_changes.sh >/dev/null 2>&1 &
Create a systemd service for automatic start and restart.
Create a systemd service file
sudo nano /etc/systemd/system/filewatch.service
Add the following content
[Unit]
Description=Monitor directory changes and send email notifications
After=network.target
[Service]
ExecStart=/usr/local/bin/watch_directories.sh
Restart=always
User=root
[Install]
WantedBy=multi-user.target
Enable and start the service
sudo systemctl enable filewatch
sudo systemctl start filewatch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment