特定のファイルが到着したら、シェルスクリプトを使用してプロセスを実行する[閉じる]

特定のファイルが到着したら、シェルスクリプトを使用してプロセスを実行する[閉じる]

「abc.csv」ファイルなどの特定のファイルが「mydir」などのディレクトリに到達したら、シェルスクリプトを使用してプロセスを実行する必要があります。

「CSVのデータをテーブルにロードするプログラムがあります。プロセスが完了すると、ソースファイルの名前が「filename」に変更されます。_最後。同じ名前のファイルを毎日複数回受信できます。 」

この場合、ディレクトリに新しいファイルが含まれるたびに、LINUX環境でシェルスクリプトを使用してプロセスを実行する必要があります。

ベストアンサー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

おすすめ記事