====== 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"
lock_file="/tmp/$(basename "${0}").lock"
# check & set lock
exec 200>${lock_file}
flock -n 200 || { echo "Another instance of this script is already running. Abort."; exit 1; }
PID=$$
echo ${PID} 1>&200
# file watch
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 after a modification
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
If you need to create some form of monitoring script/actions, maybe this snippets will help you:
[root@server ~]# systemctl is-active file_watcher.service >/dev/null && echo OK || echo NOK
OK
[root@server ~]# systemctl stop file_watcher.service
[root@server ~]# systemctl is-active file_watcher.service >/dev/null && echo OK || echo NOK
NOK