Course contentsShow
← Linux
Lesson 171 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Filesystem Event Monitoring

Trigger script logic automatically based on real-time filesystem changes.

Filesystem Event Monitoring

In this lesson, you will learn how to make your Bash scripts "listen" to your file system so they can trigger automated actions the exact moment a file is created, modified, or deleted.

The Problem with Polling

Usually, if you want to know if a file has changed, you might write a script that checks a folder every few seconds using a while loop. This is called "polling." It is inefficient because it wastes CPU cycles constantly checking for changes that rarely happen. Filesystem event monitoring solves this by letting the Linux kernel notify your script only when something actually occurs.

Using inotifywait

The industry-standard tool for this in Linux is inotifywait (part of the inotify-tools package). It acts as a bridge between the kernel's event system and your Bash logic. Instead of your script asking "Has anything changed?", your script goes to sleep until the kernel sends it a signal.

Here is a simple example of how to trigger a script when a new file is added to a directory:

#!/bin/bash
# Monitor the current directory for new file creation
inotifywait -m . -e create | while read path action file; do
    echo "The file '$file' was just created in $path!"
    # You can now call other scripts or functions here
done

How it works

  1. -m (Monitor): This flag keeps inotifywait running indefinitely instead of exiting after the first event.
  2. -e create (Event): This tells the tool to only care about the creation of new files. You could also watch for modify, delete, or move.
  3. The Pipeline: We pipe the output into a while read loop. Because inotifywait outputs text in the format directory event filename, we can capture these as variables (path, action, and file) and use them directly in our logic.

By leveraging these event-driven triggers, you can build powerful automation, such as a script that automatically compresses logs the moment they appear or updates a database whenever a configuration file is saved.

Key Takeaway: Instead of polling the filesystem, use inotifywait to create event-driven scripts that only execute logic when the kernel reports a specific change.