Search code examples
bashwatchfilesize

Using bash, how do you get alerts when a file stops being updated?


I want to be alerted, say by email, if a file does not change for x minutes.

For context, an application is running 24/7 collecting tweets on an unattended system. If the file storing the tweets doesn't change for x minutes, I need to go and check the application hasn't terminated unexpectedly.

Any ideas please? I considered watch but I am new to bash and Linux in general.


Solution

  • Use inotifywait

    #!/usr/bin/env sh
    
    MONITOREDFILE=/path/to/monitoredfile
    
    TIMEOUT=600 # 600s or 10 minutes
    
    EMAIL=user@example.com
    
    lastmodified="monitoring started on $(date -R)"
    while inotifywait \
      --quiet \
      --timeout $TIMEOUT \
      --event 'MODIFY' \
      "$MONITOREDFILE"
    do
      printf '%s has been modified before %s seconds timeout\n' \
      "$MONITOREDFILE" $TIMEOUT
      lastmodified=$(date -R)
    done
    printf '!!! ALERT !!!\nFile %s has not been modified since %s seconds\n' \
        "$MONITOREDFILE" $TIMEOUT >&2
    mailx -s "Stalled file $MONITOREDFILE" "$EMAIL" <<ENDOFMAIL
    Monitored file $MONITOREDFILE has not been modified since $lastmodified.
    ENDOFMAIL
    

    A different approach to get file last modification with GNU date, and having the loop empty:

    #!/usr/bin/env sh
    
    MONITOREDFILE=/path/to/monitoredfile
    TIMEOUT=600 # 600s or 10 minutes
    EMAIL=user@example.com
    
    while inotifywait --quiet --timeout $TIMEOUT --event 'MODIFY' "$MONITOREDFILE"
    do :;done
    lastmodified=$(date --utc --iso-8601=seconds --reference="$MONITOREDFILE")
    mailx -s "Stalled file $MONITOREDFILE" "$EMAIL" <<ENDOFMAIL
    Monitored file $MONITOREDFILE has not been modified since $lastmodified.
    ENDOFMAIL