inotify-tools: listen for changes to files
Table of Contents
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>
Options
Some of the options are:
-e <event>: specify an event, likeaccess,modify,close,openand 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, 
inotifywaitexits with an exit code of1but there are no errors. The program can also exits with this exit code when you specify themodifyevent with the-eparameter 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: