ファイル作成を検知するinotify-toolsを試しました

1.概要

ubuntu環境でファイルが作成されたことを検知する仕組みとしてinotify-toolsをネットで見つけて、検証しました。まず、どのようにして検知できるのかをLocalPCで確かめました。この内容を記述します。

2.詳細

inotify-toolsには、inotifywaitとinotifywatchが提供されますが、今回はinotifywaitに着目します

(a) インストール

参考資料に沿って、インストールします。環境はubuntu-20.04.6です。
sudo apt install inotify-tools

(b) ファイル検知設定

ローカルに検知用のディレクトリを作成します
mkdir /home/username/share

検知用shell(test.sh)を作成します
今回はファイルが完了したら検知する設定にしました。

inotifywait -m /home/username/share -e close_write |
    while read -r directory action file
    do
        echo "$directory, $action, $file"
    done

検知用shell(test.sh)を実行します

sh test.sh
Setting up watches.
Watches established.
と表示されて止まります。

(c) ファイル検知試験

別のterminalを開いて、shareディレクトリに入ります。

cd /home/username/share
touch abcd

と入力をすると、test.sh実行ターミナルには下記常時出力されます
/home/username/share/, CLOSE_WRITE,CLOSE, abcd

削除してみます
rm abcd
しかし、表示に変化はありません。

directoryを作成してみます
mkdir xyz
しかし、表示に変化はありません。

3.所見

ファイル検知設定には様々な設定ができるので、shell内で組み合せることで色々できそうです。

4.追加

(1) Google Driveでinotify-toolが利用できないか試しました

inotify-toolのinotifywaitをGoogle Driveで利用できないかと考えて試してみました。
inotifywaitには、-rのオプションを設定することでリカーシブに検知できます。これはLocalPCで確認をしました。そこで、Google DriveをGoogle-drive-ocamlfuseでmountして、リカーシブに検知できないか期待して試しました。

(a) Google Drive mount

google-drive-ocamlfuse ~/sharedrive

(b) ファイル検知設定

inotifywait -m -r ~/sharedrive -e close_write |
    while read -r directory action file
    do
        echo "$directory, $action, $file"
    done

検知用shell(test.sh)を実行します

sh test.sh
Setting up watches.
Watches established.
と表示されて止まります。

別のterminalを開いて、何かファイルを作成します。

cd ~/sharedrive
touche test.txt
しかし、検知されません。

(c) 1つのファイル検知試験

inotifywait -m ~/sharedrive/testfile.txt -e close_write |
    while read -r directory action file
    do
        echo "$directory, $action, $file"
    done

検知用shell(test.sh)を実行します

sh test.sh
Setting up watches.
Watches established.
と表示されて止まります。

cd ~/sharedrive
touche testfile.txt
これは検知できました。機能しているようです。

参考

[外部サイト参照]
inotify-toolsでファイルやディレクトリを監視する

コメント

過去30日間に良く読まれた記事

miniPCのBMAXでWindows11のsecure boot設定漏れでトラブル発生

LinuxMint/ubuntuにWine 11導入を試しました ( LinuxMint 21.3 / 22.3 ubuntu 22.04 / 26.04 Wine 11.0 / 11.6 / 11.8 / 11.13 )

Windows95/98のPCゲームをUbuntu/LinuxMintの最新PCで楽しむ方法 ( KVM / Wine / dosbox-x / midi )