当特定文件到达时,使用 Shell 脚本执行一个过程

当特定文件到达时,使用 Shell 脚本执行一个过程

当例如“abc.csv”文件的特定文件到达例如“mydir”的目录时,我需要使用 shell 脚本执行一个过程。

“有一个程序会将数据从 csv 加载到表中,一旦该过程完成,源文件将被重新命名为“文件名”_最后的。每天可能会收到多个同名文件。”

在这种情况下,每当将新文件放入目录时,都需要在 LINUX 环境下使用 shell 脚本执行该过程。

答案1

使用inotify工具(http://linux.die.net/man/1/inotifywait)。

$ cat monitor_csv.sh
if (( $# == 0)); then
   echo "Usage $0 <directory-to-monitor>"
   exit 1
fi

DIR=$1
while true;
do
    res=$(inotifywait $DIR)
    echo "Get from inotifywait: "$res
    if test -f $DIR/abc.csv; then
        echo "lauching a procedure and breaking out of the loop"
        # bash ./run_procedure.sh
        break
    else
        echo "keep watching"
    fi
done

echo "finished"

这是一个例子:

$ ./monitor_csv.sh ./mydir
Setting up watches.  
Watches established.
Get from inotifywait: ./mydir/ CREATE abc2.csv
keep watching
Setting up watches.  
Watches established.
Get from inotifywait: ./mydir/ CREATE abc.csv
lauching a procedure and breaking out of the loop
finished

可以对此脚本进行一些改进:

  1. 使用超时inotifywait

       -t <seconds>, --timeout <seconds>
              Listen for an event for the specified amount of seconds, exiting if an event has not occurred in that time.
    
  2. 指定确切的事件类型

    inotifywait -e create -e moved_to ./mydir
    

所有事件列表:

access      file or directory contents were read
modify      file or directory contents were written
attrib      file or directory attributes changed
close_write file or directory closed, after being opened in
            writeable mode
close_nowrite   file or directory closed, after being opened in
            read-only mode
close       file or directory closed, regardless of read/write mode
open        file or directory opened
moved_to    file or directory moved to watched directory
moved_from  file or directory moved from watched directory
move        file or directory moved to or from watched directory
create      file or directory created within watched directory
delete      file or directory deleted within watched directory
delete_self file or directory was deleted
unmount     file system containing file or directory unmounted

相关内容