小编典典

创建文件时执行bash脚本

linux

我正在寻找编写一个小的bash脚本,以便在启动时监视任何新创建文件的目录。如果出现新文件,我希望它的存在触发第二个脚本运行。

我看到它被用来触发压缩最近数字化的视频,并将其添加到摄取素材的日志中。

目前,我的代码如下所示:

#!/bin/sh

##VIDSTAT is a global variable coming from a parent script.
##proj is the ingestion directory coming from a parent script
proj=$1

dir="/home/$USER/data/movies/$proj"
dirlist=$(ls $dir)


while { $VIDSTAT -eq 1 }:
do
    for mov in $dirlist
    do
        if [ "$(( $(date +"%s") - $(stat -c "%Y" $mov) ))" -lt "5" ]
        then
        ~/bin/compressNlog.sh $mov
        fi
    done
done

有没有更简单/更清洁/更少内存的方式来做到这一点?

编辑 我将在每个捕获会话中更改提取目录。我已经相应地调整了代码


阅读 409

收藏
2020-06-03

共1个答案

小编典典

Incron 怎么样?它在文件/目录更改时触发命令。

sudo apt-get install incron

例:

<path> <mask> <command>

在哪里<path>可以查看目录(意味着监视目录和/或直接在该目录中的文件(不是监视该目录的子目录中的文件!))或文件。

<mask> 可以是以下之一:

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>是事件发生时应运行的命令。在命令规范中可以使用以下通配符:

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

如果查看目录,则$ @保留目录路径,$#保留触发事件的文件。如果您观看文件,则$ @拥有文件的完整路径,而$#为空。

工作示例:

$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文件中添加以下行:

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