User Tools

Site Tools


os:linux:file_watcher_service

This is an old revision of the document!


File Watcher Service

On CentOS/RHEL: Setup the epel repository and install inotify-tools, according to https://github.com/inotify-tools/inotify-tools/wiki.

yum install -y epel-release && yum update
yum install inotify-tools

Create a new shell script.

vim /usr/local/bin/file_watcher

Example code. Add the actions you need, after a file change is detected. Change the file name.

#!/usr/bin/env bash
file_name="/tmp/watched_file.txt"
log_file="/tmp/$(basename ${0}).log"
while true; do
    inotifywait -e modify ${file_name}
    echo "[$(date --iso-8601=seconds)] change detected on file ${file_name}" >> ${log_file}
    # maybe do some other actions
done

Create a systemd service file for the shell script.

vim /etc/systemd/system/file_watcher.service

If the file is modified by a service, change the After parameter to the according service.

[Unit]
Description=Watches a specific file for changes
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/file_watcher
Restart=on-failure
RestartSec=3

[Install]
WantedBy=multi-user.target

Reload systemd and start the new service.

systemctl daemon-reload
systemctl start file_watcher.service
os/linux/file_watcher_service.1607125743.txt.gz · Last modified: 2020-12-05 00:49 by Manuel Frei