您的位置:首页 > 运维架构 > Linux

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

2013-09-08 20:51 453 查看
当我在建一个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里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: