大纲
Inotify 它是在内核 2.6.13 版本中引入的一个新功能,它为用户态监视文件系统的变化提供了强大的支持,允许监控程序打开一个独立文件描述符,并针对事件集监控一个或者多个文件,例如打开、关闭、移动/重命名、删除、创建或者改变属性。
inotify 可以监控文件的变化,使用场景适合监视配置文件变化,后触发重启程序
安装inotify
以Ubuntu为例子
可能需要安装 gcc cmake libc6-dev
wget http://nchc.dl.sourceforge.net/project/inotify-tools/inotify-tools/3.13/inotify-tools-3.13.tar.gz
./configure
make && make install
自动安装到
/usr/local/bin/inotifywait
/usr/local/bin/inotifywatch
inotifywait 仅执行阻塞,等待 inotify 事件,你可以使用它来监控任何一组文件和目录,或监控整个目录树(目录、子目录、子目录的子目录等等),并且可以结合 shell 脚本,更好的使用 inotifywait。
inotifywatch 用来收集关于被监视的文件系统的统计数据,包括每个 inotify 事件发生多少次。
主要有以下几个配置参数
-e 指定要监视的事件
–format
例如
输出 时间 变化的文件夹 文件 事件
–format ‘%T %w %f %e’
监听文件夹的变化
inotifywait -e modify,move,create,delete -mr /ops/tmp/
监听文件夹的变化,指定时间格式,输出各式
inotifywait -e modify,move,create,delete -mr --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %w %f %e' /ops/tmp/
可以把命令编写成一个脚本,并把内容输入到变量中,基于条件处理
#!/bin/bash
configfile='.conf$'inotifywait -e modify,delete -mr --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %w %f %e' /ops/tmp/ | while read day time folder file event;
do# echo $time $folder $file $eventif [[ $file =~ $configfile ]]; thenecho "is .conf file "$file $eventfi
done
注意 if中使用正则表达式,需要使用[[]]括起来