Bash – How to make a script run like a daemon waiting for changes in 2 files

bashdaemoninotifyscripting

I am new to scripting, I made a script that reads 2 files and execute commands and as output a log file.

I want this script to run like a daemon and wait for changes in these 2 files to execute these commands again on theses files.

I am aware of using some inotify, but I don't know exactly how to use it and where to place the loop so the script will work as I want it too, that is:

  1. user executes the script for the first time
  2. this script reads these files and make the output log
  3. the script "sleeps" (daemonized) until these 2 log files change (some lines added to them)
  4. execute the same script again on these files
  5. sleep again and wait for changes in these 2 files

Best Answer

I had to monitor an old software, which does not have enough logging options. It is not exactly what you want, but might help you.

  • compares 2 files (ref.cfg and cur.cfg) every second
  • logs to file cfg.log if a diff is detected
  • makes a diff to a file if a change is detected
  • makes a backup of the file with date suffix

watch_cfg.sh:

#!/bin/bash

cfg_reference="/tmp/ref.cfg"
cfg_current="/tmp/cur.cfg"

while true; 
do 
  cfg1=$(cat $cfg_reference)
  cfg2=$(cat $cfg_current)
  date_current="$(date +"%F_%T")"
  diff_detected=false
  test "$cfg1" = "$cfg2" || diff_detected=true
  if [ "$diff_detected" = true ]; then
    printf "$date_current [cfg] diff detected\n" >> cfg.log
    diff $cfg_reference $ecfg_current > "./cfg_diff/cur.cfg_${date_current}"
    cp -a "$cfg_reference" "./cfg_old/cur.cfg_before_${date_current}"
    cp -a "$cfg_current" "$cfg_reference"
  fi
  sleep 1
done

Run those commands:

chmod +x watch_cfg.sh
nohup ./watch_cfg.sh  > /dev/null 2>&1 &

This detaches the process from the current session and sends it to the background.

Related Question