DEV Community

Cover image for Monitor & React to File System Events on Linux Using inotify
Maulik
Maulik

Posted on

Monitor & React to File System Events on Linux Using inotify

Ever wondered when you make a change in a single file and on saving it some tools like angular or other clis or nodemon automatically react to it by bundling and redeploying the application?

Also while using an ide, when you do some mistake in code and save it, all the dependent files turn red due to an error!

The reaction is coded on ide or cli...but how they keep a watch on files and How it gets to know about events like create, modified, deleted and How we can custom automate something.

I needed such a tool that can listen to the file change events as I was using AngularJS and it does not have an inbuilt cli as angular2+ has. So I looked for something that can help me to automate the build. I use ubuntu so I searched and I found the tool named inotify.

I achieved the hot deploy feature by using the inotify with a bash script. I have written a shell script like below
Alt Text
or check out this git repo

GitHub logo Maulikdes / file_watcher

This project is a shell script file that can be used to watch the file changes and automate the actions

I just have to now run the following command and not have to do the manual steps I was doing after changing files

bash filename.sh

I'm not gonna bore you by writing about more functionalities, and stuff of inotify but let's just take a look at the simple example
First to install the inotify, just hit the following command

sudo apt-get install -y inotify-tools

Here is a simple bash script which watches the changes of a file name a.txt and on change, it writes the log to b.txt

while true; do
    # the next statement will wait for the inotify event to get triggered
    change=$(inotifywait -e modify a.txt)
    # append he change log to the b.txt file
    echo $change "$(date +"%T")" >> b.txt;
done
Enter fullscreen mode Exit fullscreen mode

Now let's see the demo

Top comments (0)