如何使用inotify自动删除linux中创建的文件?

Mil*_*ike 5 linux inotify

我试图用inotify删除创建的文件,但它不起作用:

inotifywait -r --format '%w%f' -e create /test && rm $FILE
Run Code Online (Sandbox Code Playgroud)

当我在/ test中创建一个文件时,我得到了这个:

/test/somefile.txt
rm: missing operand
Try `rm --help' for more information.
Run Code Online (Sandbox Code Playgroud)

所以似乎$ FILE变量没有传递给rm命令......我怎么能正确地做到这一点?谢谢.

Céd*_*ien 6

启动inotifywait一次(没有-m标志)时,您可以轻松使用xargs:

inotifywait -r --format '%w%f' -e create /test -q | xargs /bin/rm
Run Code Online (Sandbox Code Playgroud)

等待在/ test中创建文件,将文件名提供给xargs并给这个arg /bin/rm删除文件,然后退出.

如果需要连续观察目录(使用inotifywait的-m参数),请创建如下脚本文件:

inotifywait -m -r --format '%w%f' -e create /test | while read FILE
do
        /bin/rm $FILE
done
Run Code Online (Sandbox Code Playgroud)

然后,将删除在您/ test目录中创建的每个新文件.