且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在创建文件时执行 bash 脚本

更新时间:2023-10-17 19:41:10

incron 怎么样?它触发文件/目录更改命令.

How about incron? It triggering Commands On File/Directory Changes.

sudo apt-get install incron

示例:

<path> <mask> <command>

其中 <path> 可以是目录(意味着该目录和/或直接在该目录中的文件(不是该目录的子目录中的文件!)被监视)或文件.

Where <path> can be a directory (meaning the directory and/or the files directly in that directory (not files in subdirectories of that directory!) are watched) or a file.

可以是以下之一:

IN_ACCESS           File was accessed (read) (*)
IN_ATTRIB           Metadata changed (permissions, timestamps, extended attributes, etc.) (*)
IN_CLOSE_WRITE      File opened for writing was closed (*)
IN_CLOSE_NOWRITE    File not opened for writing was closed (*)
IN_CREATE           File/directory created in watched directory (*)
IN_DELETE           File/directory deleted from watched directory (*)
IN_DELETE_SELF           Watched file/directory was itself deleted
IN_MODIFY           File was modified (*)
IN_MOVE_SELF        Watched file/directory was itself moved
IN_MOVED_FROM       File moved out of watched directory (*)
IN_MOVED_TO         File moved into watched directory (*)
IN_OPEN             File was opened (*)

是事件发生时应该运行的命令.在命令规范中可以使用以下通配符:

<command> is the command that should be run when the event occurs. The following wildards may be used inside the command specification:

$$   dollar sign
$@   watched filesystem path (see above)
$#   event-related file name
$%   event flags (textually)
$&   event flags (numerically)

如果你观察一个目录,那么 $@ 保存目录路径和 $# 触发事件的文件.如果您查看文件,则 $@ 保存文件的完整路径,而 $# 为空.

If you watch a directory, then $@ holds the directory path and $# the file that triggered the event. If you watch a file, then $@ holds the complete path to the file and $# is empty.

工作示例:

$sudo echo spatel > /etc/incron.allow
$sudo echo root > /etc/incron.allow

启动守护进程:

$sudo /etc/init.d/incrond start

编辑incrontab文件

$incrontab -e
/home/spatel IN_CLOSE_WRITE touch /tmp/incrontest-$#

测试一下

$touch /home/spatel/alpha

结果:

$ls -l /tmp/*alpha*
-rw-r--r-- 1 spatel spatel 0 Feb  4 12:32 /tmp/incrontest-alpha

注意:Ubuntu 中,您需要在启动时激活 inotify.请在 Grub menu.lst 文件中添加以下行:

Notes: In Ubuntu you need to activate inotify at boot time. Please add following line in Grub menu.lst file:

kernel /boot/vmlinuz-2.6.26-1-686 root=/dev/sda1 ro inotify=yes