LoginSignup
3
1

More than 3 years have passed since last update.

【ラズパイ】ディレクトリを継続的に監視して変更をフックで任意のシェルを走らせる方法

Last updated at Posted at 2020-08-08

Raspberry Pi 3B(以下:ラズパイ)で、指定ディレクトリ内を監視して更新されたら任意の処理を走らせるという事をしたいと思います。

  • フック : Aディレクトリに画像が保存される
  • する事 : AディレクトリとBディレクトリの状態を同期

具体的には上記のような事をするためにinotify-toolsを使用しします。

inotify-toolsのインストール

apt-getでインストールします。

$ sudo apt-get install inotify-tools

inotyfywaitコマンドで監視

inotyfywait -e 【イベント】 【監視するディレクトリ】

inotfywaitコマンドで特定イベントと監視するディレクトリを指定します。
今回はmoved_to(対象ディレクトリ内へ移動された)イベントの監視をして処理をさせます。

inotify_single.sh
#!/bin/sh

inotifywait -m -e moved_to A | \
    rsync -rv A B

ryncコマンドを使ってAとBを同期させています。

-mオプションについて

-mオプションをつけないとが初回のイベント発行でinotifywaitが終了してしまうので付けています。

継続的に監視する

このままだと一連のイベントが通知されると監視が終了してしまいますので処理を修正します。

inotify_continuous.sh
#!/bin/sh

inotifywait -m -e moved_to A | \
    while read _; do
        rsync -rv A B
    done

このようにwhile文を使って継続的に監視するようにしています。

環境

  • Raspberry Pi 3B
  • Raspbian GNU/Linux 9.8 (stretch)
  • inotifywait 3.141

参考


  1. inotifywaitのバージョンは inotifywait -hlで確認できます 

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1