inotify-tools: listen for changes to files
inotify-tools
is a set of utilities for monitoring file or folder changes (access, modification, and more events).
The main utility is called inotifywait
. As you can imagine, this program waits until a file or folder has changed in some way. Then, it exits or it continues executing until killed. It’s useful in scripts, when you want something happens when a file is modified.
inotifywait [<options>] <file or folder>
Table of Contents
Options
Some of the options are:
-e <event>
: specify an event, likeaccess
,modify
,close
,open
and more.-t <seconds>
: exit if no event has ocurred within<seconds>
.-r
: recursive mode, look for changes on all subdirectories of the folder passed as argument toinotifywait
.-m
: monitor, continues executing after receiving events.- Check man page for more.
Examples
- A simple command that will exits when an event happens.
$ inotifywait test.csv Setting up watches. Watches established. OPEN
-
This process will continue until manually killed.
$ inotifywait -m test.csv Setting up watches. Watches established. OPEN CLOSE_NOWRITE,CLOSE OPEN ACCESS ACCESS CLOSE_NOWRITE,CLOSE
-
This is a script that listens for file modification and syncs the file with a cloud storage (in this case, AWS S3).
#!/bin/bash synchronize_file(){ inotifywait -e modify /home/user/Documents/file.txt aws s3 cp /home/user/Documents/file.txt s3://mybucket/file.txt && synchronize_file } synhronize_file
Troubleshooting
- In older versions,
inotifywait
exits with an exit code of1
but there are no errors. The program can also exits with this exit code when you specify themodify
event with the-e
parameter and you modify the file. I don’t know why, because if you specify another event likeopen
, it will exit with an exit code of0
(if you open the watched file).
If you have any suggestion, feel free to contact me via social media or email.
Latest tutorials and articles:
Featured content: