linux-监视目录中的新文件,然后运行脚本 [英] linux - watch a directory for new files, then run a script
问题描述
我想查看Ubuntu 14.04中的目录,并在该目录中创建新文件时运行脚本.
I want to watch a directory in Ubuntu 14.04, and when a new file is created in this directory, run a script.
具体来说,我有一些安全摄像机,当它们检测到运动时会通过FTP捕获的视频上传.我想在此FTP服务器上运行脚本,以便在创建新文件时将它们立即镜像(上传)到云存储服务,这是通过我已经编写的脚本完成的.
specifically I have security cameras that upload via FTP captured video when they detect motion. I want to run a script on this FTP server so when new files are created, they get mirrored (uploaded) to a cloud storage service immediately, which is done via a script I've already written.
我发现iWatch使我可以做到这一点( http://iwatch.sourceforge.net/index.html )-我遇到的问题是,即使在文件仍在上传的过程中,iwatch也会在FTP目录中创建文件后立即启动云上传脚本.这会导致云同步脚本上传0字节的文件,这对我来说毫无用处.
I found iWatch which lets me do this (http://iwatch.sourceforge.net/index.html) - the problem I am having is that iwatch immediately kicks off the cloud upload script the instant the file is created in the FTP directory, even while the file is in progress of being uploaded still. This causes the cloud sync script to upload 0-byte files, useless to me.
也许我可以在云上传脚本中添加一个"wait",但是似乎很麻烦,并且无法预测要等待多长时间,这取决于文件大小,网络条件等.
I could add a 'wait' in the cloud upload script maybe but it seems hack-y and impossible to predict how long to wait as it depends on file size, network conditions etc.
有什么更好的方法?
推荐答案
尽管注释中提到了inotifywait
,但完整的解决方案可能对其他人有用.这似乎可行:
Although inotifywait
was mentioned in comments, a complete solution might be useful to others. This seems to be working:
inotifywait -m -e close_write /tmp/upload/ | gawk '{print $1$3; fflush()}' | xargs -L 1 yourCommandHere
将运行
yourCommandHere /tmp/upload/filename
新上载的文件关闭时
注意:
-
inotifywait
是Ubuntu中apt软件包inotify-tools
的一部分.它使用内核inotify服务监视文件或目录事件 -
-m
选项为监视模式,每个事件向标准输出输出一行 -
-e close_write
表示打开以进行写入的文件的文件关闭事件.文件关闭事件有望避免收到不完整的文件. -
/tmp/upload
可以替换为其他要监视的目录 - 通向
gawk
的管道重新格式化inotifywait
输出行以删除第二列,这是事件类型的重复.它将第1列中的目录名与第3列中的文件名结合在一起,以换行,并刷新每一行以消除缓冲并鼓励xargs
-
xargs
获取文件列表并为每个文件运行给定的命令,并在命令末尾附加文件名.-L 1
导致xargs在标准输入接收到的每一行之后运行.
inotifywait
is part of apt packageinotify-tools
in Ubuntu. It uses the kernel inotify service to monitor file or directory events-m
option is monitor mode, outputs one line per event to stdout-e close_write
for file close events for files that were open for writing. File close events hopefully avoid receiving incomplete files./tmp/upload
can be replaced with some other directory to monitor- the pipe to
gawk
reformats theinotifywait
output lines to drop the 2nd column, which is a repeat of the event type. It combines the dirname in column 1 with the filename in column 3 to make a new line, which is flushed every line to defeat buffering and encourage immediate action byxargs
xargs
takes a list of files and runs the given command for each file, appending the filename on the end of the command.-L 1
causes xargs to run after each line received on standard input.
这篇关于linux-监视目录中的新文件,然后运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!