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
-m(Monitor): This flag keepsinotifywaitrunning indefinitely instead of exiting after the first event.-e create(Event): This tells the tool to only care about the creation of new files. You could also watch formodify,delete, ormove.- The Pipeline: We pipe the output into a
while readloop. Becauseinotifywaitoutputs text in the formatdirectory event filename, we can capture these as variables (path,action, andfile) 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.