Executing a bash script upon file creation

后端 未结 3 829
既然无缘
既然无缘 2020-12-08 17:57

I am looking write a small bash script to, when launched, watch a directory for any newly created files. If a new file appears, I want its presence to trigger a second scrip

3条回答
  •  攒了一身酷
    2020-12-08 18:23

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

    sudo apt-get install incron
    

    Example:

      
    

    Where 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.

    can be one of the following:

    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 (*)
    

    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.

    Working Example:

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

    Start Daemon:

    $sudo /etc/init.d/incrond start
    

    Edit incrontab file

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

    Test it

    $touch /home/spatel/alpha
    

    Result:

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

    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
    

提交回复
热议问题