Course contentsShow
← Linux
Lesson 1286 of 1,81911. Automation and System SchedulingFree lesson

Introduction to Inotify and File Events

Monitor filesystem changes in real-time to trigger automated workflows.

In this lesson, you will learn how to move beyond time-based automation and instead trigger workflows the exact moment a file changes on your system using inotify.

Why move beyond Timers?

So far, we have relied on cron and systemd timers to run tasks at specific intervals. This approach works well for routine maintenance, but it is inefficient for tasks that depend on file availability—such as processing a new log, uploading an image, or updating a configuration. Checking every minute wastes CPU cycles if nothing has happened, and introduces a delay if you need a near-instant response.

The Inotify Mechanism

inotify (inode notify) is a Linux kernel subsystem that allows applications to "watch" files or directories for specific events. Instead of the system polling the disk to ask, "Did anything change?", the kernel pushes a notification to your script the moment an action—like a file creation, modification, or deletion—occurs.

To interact with this subsystem, we typically use the inotify-tools package, specifically the inotifywait command.

Putting it into practice

Imagine you have a directory where a remote service drops incoming data files, and you want to process them immediately. You can write a small loop to react to these changes:

# Monitor a directory for 'close_write' events (when a file is finished saving)
inotifywait -m /path/to/data -e close_write | while read path action file; do
    echo "Processing $file detected in $path..."
    ./process_data.sh "$path/$file"
done

In this example:

  • -m keeps the monitor running (it doesn't exit after the first event).
  • -e close_write narrows the focus to only events where a file was successfully written and closed.
  • The while loop pipes the output into a processing script, allowing your automation to remain dormant until the kernel sends a signal that a file is ready.

This event-driven model is significantly more efficient than a timer. It ensures your automation responds immediately without needing to constantly re-scan directories, making your system quieter and more responsive.

Key Takeaway: Inotify allows you to transition from inefficient, time-based polling to event-driven automation that triggers tasks exactly when file system changes occur.