fsnotifywait - Linux


Overview

fsnotifywait is a command for monitoring file system events and triggering actions based on those events. It continuously watches a specified directory and its subdirectories for changes and reports them in real-time. This makes it a valuable tool for automating tasks such as triggering scripts, sending notifications, or performing backups whenever file system changes occur.

Syntax

fsnotifywait [OPTIONS] <path> [<path> ...]

Options/Flags

  • -a, –all | Monitor all files and directories
  • -q, –quiet | Suppress non-error messages
  • -m, –monitor | Continuously monitor, even if no events occur
  • -t, –timeout= | Timeout after specified number of seconds
  • -u, –unlocked | Do not hold a lock on the watched files
  • -e, –event-filter= | Filter events by type (e.g., create, delete, modify)
  • -f, –format= | Output format (e.g., JSON, text)
  • -c, –command= | Command to execute when an event occurs
  • –help | Display help and exit
  • –version | Display version and exit

Examples

Monitor a directory for file changes and print event details:

fsnotifywait /home/user/some-directory

Execute a script when a file is created:

fsnotifywait -e create -c '/bin/sh /path/to/script.sh' /home/user/some-directory

Monitor multiple directories and send email on file modifications:

watch -d 'fsnotifywait -m -e modify /path/to/dir1 /path/to/dir2 && mail -s "File Modified" my.email@example.com'

Common Issues

Permission denied errors: Ensure you have read permissions to the specified directories.

No output: Verify the command is not in a locked state (use -m to keep it running).

Integration

With rsync: Trigger rsync backups on file changes:

rsync -a --delete --bwlimit=102400 /home/user/some-directory /backup/some-directory &
fsnotifywait -e modify -c 'kill `pidof rsync`' /home/user/some-directory

Related Commands

  • inotifywait: Similar command with more advanced features, but requires root privileges.
  • fswatch: File system monitoring tool with a graphical user interface.
  • watchman: File system monitoring for development workflows.