有两个思路,一是直接循环遍历,如
while sleep 10; do
#do something you want ...
done
简单康粗暴且有效。
二是借助于inotify-tools.首先请确保inotify-tools
已安装。
使用incron
来调用处理脚本。
The user table rows have the following syntax (use one or more spaces between elements):
<path> <mask> <command>
Where:
-
<path>
是文件系统路径(每个空格必须以反斜杠开头)
-
<mask>
是符号(请参见inotify.h
;使用逗号分隔符号)或事件的数字掩码
-
<command>
是要在事件上运行的应用程序或脚本
该命令可能包含以下通配符:
-
$$
- 美元符号
-
$@
- 监视的文件系统路径
-
$#
- 与事件相关的文件名
-
$%
- 文本事件标志
-
$&
- 数字事件标志
掩码可能还包含一个特殊符号IN_NO_LOOP
,该符号禁用在处理事件期间发生的事件(以避免循环).
示例:'abc'
每次在中更改文件时,都需要使用完整文件路径作为参数来运行程序/var/mail
。解决方案之一如下:
/var/mail IN_CLOSE_WRITE abc $@/$#
也可以使用 inotifywait
如:
logOfChanges="/tmp/changes.log.csv" # 用于记录目录发生的变动.
# 后台执行 inotifywait 来监控 $DIR 目录发生的变动
inotifywait -mrcq $DIR > "$logOfChanges" &
IN_PID=$$
# 这里进行你希望的处理
...
# Kill and analyze
kill $IN_PID
while read entry; do
# Split your CSV, but beware that file names may contain spaces too.
# Just look up how to parse CSV with bash. :)
path=...
event=...
... # Other stuff like time stamps?
# Depending on the event…
case "$event" in
SOME_EVENT) myHandlingCode path ;;
...
*) myDefaultHandlingCode path ;;
done < "$logOfChanges"
inotifywait
输入参数也可以使用--format
,而不是-c
。
更多的相关信息请查阅 man inotifywait
与man inotifywatch
。
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…