Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to automatically delete created file in linux with inotify?

Tags:

linux

inotify

I am trying to delete a created file with inotify but it doesn't work:

inotifywait -r --format '%w%f' -e create /test && rm $FILE

when i create a file in /test I get this:

/test/somefile.txt
rm: missing operand
Try `rm --help' for more information.

so it seems that the $FILE variable is not passed to the rm command... how can I do this correctly? Thanks.

like image 219
MilMike Avatar asked Nov 29 '11 17:11

MilMike


People also ask

How inotify works in Linux?

How does Inotify Work? The Inotify develops a mechanism for monitoring file system events, which watches individual files & directories. While monitoring directory, it will return events for that directory as well as for files inside the directory.

What is inotify used for?

inotify (inode notify) is a Linux kernel subsystem created by John McCutchan, which monitors changes to the filesystem, and reports those changes to applications. It can be used to automatically update directory views, reload configuration files, log changes, backup, synchronize, and upload.

What is inotify watch?

Inotify Watch helps to keep track of the file changes under the directories on “watch” and report back to the application in a standard format using the API calls. We can monitor multiple file events under the watched directory using the API calls.


1 Answers

When launching your inotifywait once (without the -m flag), you can easily use xargs :

inotifywait -r --format '%w%f' -e create /test -q | xargs /bin/rm

that will wait for a file creation in /test, give the filename to xargs and give this arg to /bin/rm to delete the file, then it will exit.

If you need to continuously watch your directory (with the -m param of inotifywait), create a script file like this :

inotifywait -m -r --format '%w%f' -e create /test | while read FILE
do
        /bin/rm $FILE
done

And then, every newly file created in you /test directory will be removed.

like image 77
Cédric Julien Avatar answered Nov 15 '22 14:11

Cédric Julien