This tutorial will show you how to use Linux filesystem events (notify) to get notified every time a file appears in a directory. You could use these as triggers to automate common tasks on your system.
We’re going to write a script that watches a directory and acts on new files that are added. Each file is gzipped and moved to another directory, as soon as it is detected. The script uses the inotify subsystem, through a utility called inotify-tools. But first, let’s install the tool and experiment.
Installing inotify-tools and gzip
Use apt-get
to install this package onto your system if you’re using Ubuntu or another Debian-based distribution. On other Linux distributions, use your Linux distribution’s package management tool instead.
sudo apt-get install inotify-tools gzip
Experimenting with inotify-tools
Let’s begin by watching a directory and seeing what events initiate when new files arrive. We will use a tool called inotifywatch
, which is part of inotify-tools. Create a new directory called “incoming”:
mkdir incoming
Start watching this directory by executing the following command:
inotifywatch -v incoming
This will instruct inotify to watch for all filesystem events in the “incoming” directory. The -v
option makes the tool print out extra information about what it’s doing. We haven’t specified a timeout option (-t
), and the command will keep gathering events until we exit with CTRL+C. At this point, our terminal should look something like this:
Open a new terminal window (or tab) and change to the incoming directory. Use the touch command to create a new file named “newfile.”
cd incoming/ touch newfile
Now go back to the first terminal window and stop inotifywatch by hitting CTRL+C.
Read the remaining 19 paragraphs
Source : How to Perform a Task When a New File is Added to a Directory in Linux