На информационном ресурсе применяются рекомендательные технологии (информационные технологии предоставления информации на основе сбора, систематизации и анализа сведений, относящихся к предпочтениям пользователей сети "Интернет", находящихся на территории Российской Федерации)

Feedbox

12 подписчиков

How to Perform a Task When a New File is Added to a Directory in Linux

Author: Taylor Gibb / Source: How-To Geek

Bash shell on Ubuntu PC concept
Fatmawati Achmad Zaenuri/Shutterstock.com

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.

A table of events will be served to the console, indicating one instance of “create,” “open,” “attrib,” and “close_write.” These four events occurred when we used touch to create a new file, set its file access attributes, opened it to write a null terminating character, and then closed it afterward. These are just a few of the multitude of…

Click here to read more

The post How to Perform a Task When a New File is Added to a Directory in Linux appeared first on FeedBox.

Ссылка на первоисточник
наверх