[Raspberry Pi] How to continuously monitor directories and run arbitrary shells with hooks for changes

With Raspberry Pi 3B (hereinafter: Raspberry Pi), I would like to ** monitor the specified directory ** and run arbitrary processing when it is updated.

--Hook: Image is saved in A directory --What to do: Synchronize the state of A and B directories

Specifically, use ** inotify-tools ** to do something like the above.

Install inotify-tools

Install with apt-get.

$ sudo apt-get install inotify-tools

Monitor with the inotyfy wait command

ʻInotyfywait -e [Event] [Monitoring directory] `

Specify the specific event and the directory to be monitored with the inotfywait command. This time, the moved_to (moved into the target directory) event is monitored and processed.

inotify_single.sh


#!/bin/sh

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

I'm using the rsync command to synchronize A and B.

About the -m option

If you do not add the -m option, inotifywait will end when the first event is issued, so it is added.

Continuously monitor

If this is left as it is, monitoring will end when a series of events are notified, so correct the process.

inotify_continuous.sh


#!/bin/sh

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

In this way, the while statement is used to continuously monitor.

environment

[^ 1]: You can check the version of inotifywait with ʻinotifywait -hl`

reference

-Monitor files and directories with inotify-tools

Recommended Posts

[Raspberry Pi] How to continuously monitor directories and run arbitrary shells with hooks for changes
Easy IoT to start with Raspberry Pi and MESH
Easy introduction to home hack with Raspberry Pi and discord.py
Update Python for Raspberry Pi to 3.7 or later with pyenv
I made a resource monitor for Raspberry Pi with a spreadsheet
How to put OpenCV in Raspberry Pi and easily collect images of face detection results with Python
Try fishing for smelt with Raspberry Pi
How to install NumPy on Raspberry Pi
How to use Service Account OAuth and API with Google API Client for python
[For beginners] I made a motion sensor with Raspberry Pi and notified LINE!
I tried to create a button for Slack with Raspberry Pi + Tact Switch
How to use Raspberry Pi pie camera Python
How to add arbitrary headers to response with FastAPI
MQTT RC car with Arduino and Raspberry Pi
How to switch between Linux and Mac shells
How to display images continuously with matplotlib Note
Get temperature and humidity with DHT11 and Raspberry Pi
Connect to MySQL with Python on Raspberry Pi
Control music playback on a smartphone connected to Raspberry Pi 3 and bluetooth with AVRCP
How to make an arbitrary DictCursor with PyMySQL and not return None when NULL