现在的位置: 首页 > 综合 > 正文

Linux利用inotify-tools的inotifywait实现:当文件夹内容改变时自动执行一段脚本

2014年08月12日 ⁄ 综合 ⁄ 共 973字 ⁄ 字号 评论关闭

当我在建一个rpm包管理服务器时,里面有个这样的要求,要求当有新的rpm存入指定目录时,自动执行一段脚本去对这个rpm包进行检测。

这里利用了inotify-tools的inotifywait的模块,里面有个事件处理的参数-e,见它的手册。

我的代码如下:

#/bin/bash
################################################################
#  automatically run a script(action.sh) when the contents
#     of a directory (${EVENTPATH}) changed.
#  pls. install the inotify-tools-3.13-1.el4.rf.i386.rpm module
#       before use this scripts
#  Aborn Jiang (aborn.jiang@gmail.com)
#  Sep.8, 2013
################################################################

EVENTPATH="."
MSG=".inotifymsg"
PATTERN=".rpm$"          # only when the rpm files changed.
while inotifywait -e modify -e create -e delete -e moved_to -e moved_from \
                   ${EVENTPATH} 1>${EVENTPATH}/${MSG} 2>/dev/null;
do
        FILE=`cat $EVENTPATH/${MSG} |egrep ${PATTERN} | awk '{print $3}' `
        ACTION=`cat $EVENTPATH/${MSG} |egrep ${PATTERN} | awk '{print $2}' `
        [ ! -z ${FILE} ] && \
        echo "in the directory ${EVENTPATH}, the file: ${FILE} modified,  action:${ACTION} " && \
        ./action.sh
done

我这里是只检测是不是有rpm变动,你可以修改代码里的PATTERN变量内容,就可以检测任何文件!如果你要检测任何文件,你可以把PATTERN设置为“*”

我的执行脚本放在action.sh里

【上篇】
【下篇】

抱歉!评论已关闭.