X

using inotify-tools to trigger events

inotify-tools

What are Inotify-tools?

Inotify-tools is a C libary that interface with the inotify kernel function. Inotify-tools are available on kernels later than 2.6.13.  These tools can monitor or act based on file system events, this is particularly useful for scripting out actions you would like to happen if an event takes place.

Install on Fedora / CentOS / RedHat:

Install the epel repo:

yum install epel-release

Install inotify tools:

yum install inotify-tools

Install on Debian / Ubuntu:

apt-get install inotify-tools

After installing you have access to inotifywait

Inotifywait this watches for inotify events, it can watch a specific, directory, or a recursive directory tree. By default inotifywait checks for all events to the monitored file or directory

The Inotify sytanx is:

inotify filename
Inotify example:
 [root@server ~]$ inotifywait /test
 Setting up watches.
 Watches established.
 /tmp/ MODIFY test

List of Inotifywait events you can watch for:

access – A file being monitored was ready from.
modify – A file being monitored was written to.
attrib – An attribute (timestamps, file permissions, attributes) of a monitored file were changed
close_write –  A file being monitored was closed after being in a writable state
close – A file being monitored was closed
open – A file being monitored was opened
moved_to –  A file was moved into a monitored directory
moved_from – A file or directory was moved
delete – A file or directory within a watched directory was deleted
delete_self  – A monitored file or directory was deleted, after this the file and or directory is no longer being monitored.
umount – the file sytem was unmounted that the monitored file/folder was on.

Full Example of Inotifywait:
## script to detect new files
WATCHDIR='/tmp/';
OUTDIR='/tmp-new';
inotifywait -m -q -e close_write --format %f ${WATCHDIR} | while IFS= read -r file; do
cp -p ${WATCHDIR}/"$file" ${OUTDIR}/
done

-m stands for monitor(by default inotifywait will close after the first event)
-r means recursively

A script like this, could also be placed in /etc/rc.local to start at boot.

LinuxAdmin.io
0 0 votes
Article Rating
LinuxAdmin.io:
Related Post