When you are managing a secure Linux server, you often need to know the exact moment a critical configuration file (like /etc/passwd) is modified, or the exact moment a user uploads a new image into a specific web directory. Writing a bash script that constantly loops and uses the ls command to check for new files is incredibly inefficient; it consumes excessive CPU cycles and causes disk thrashing. The professional way to monitor for file system activity is to tap directly into the Linux kernel’s internal event queue using the inotifywait command.
How the inotify Subsystem Works
The Linux kernel contains a native subsystem called inotify. Whenever any piece of software interacts with a file (opening it, reading it, writing to it, or deleting it), the kernel generates a tiny internal alert. The inotifywait command simply listens for these alerts, meaning it uses virtually zero CPU or RAM while it waits.
To use this tool on a Debian/Ubuntu system, you must first install the package: sudo apt install inotify-tools.
How to Monitor a File or Directory
You can instruct the command to watch a single file or an entire directory structure.
To watch an upload directory for any new files being created, use the -m (monitor) flag to keep the command running continuously, and the -e (event) flag to filter for specific actions:
inotifywait -m -e create /var/www/uploads/
The terminal will freeze. The moment an FTP user or a PHP script drops a new file into that folder, the terminal will instantly output a line of text indicating the exact filename that was created. It will then go back to sleep, waiting for the next event.
If you are debugging a security issue and want to know if a hacker’s script is secretly reading the system password file, you can monitor the file for “access” events:
inotifywait -m -e access /etc/passwd
Every time a user or process simply reads the file, the terminal will alert you.
Using inotifywait in Bash Scripts
While watching the terminal is useful for debugging, the true power of inotifywait lies in shell scripting. You can use it as an ultra-efficient trigger mechanism to launch other commands.
For example, you could write a small script that monitors a directory. The script uses inotifywait to pause execution. The moment a user drops a massive .WAV audio file into the directory, inotifywait detects the “close_write” event (meaning the upload finished successfully), wakes up the script, and instantly triggers FFmpeg to compress the file into an MP3.