I have set up a very simple script so that I can test whether a process is running or not and if so then it will touch a file and everything will be fine. However if process is not running and file isn't touched then I want to be able to set up an alert. pgrep sleep >/dev/null && touch monitor.logThis script is running in a crontab every minute. I need a way for it to alert if file has not been touched? Is this possible? Thanks
Creating alert notification if process stops touching file
shell script;scripting;monitoring;touch
This is a straightforward file modification time check; the complications mainly arise from the possibility of up to 86,400 alerts per day (usually over a long holiday weekend is when these sorts of thing break), and additional complications of whether or not the modification time checker (or cron, or the system...) are actually running, whether the host clock is correct (time skew on virts, BIOS clock coming up four years in the future, broken NTP, etc).#!/bin/sh# what we're checking for mtime changes straying from the current system timeMONITOR=foofileTHRESHOLD=60# use mtime on this file to avoid frequent alert spam should the above stop# being updatedLAST_ALERT=barfileLAST_ALERT_THRESHOLD=60NOW_MTIME=`date +%s`absmtimedelta() {    delta=`expr $NOW_MTIME - $1`    # absolute delta, in the event the mtime is wrong on the other side of    # the current time    echo $delta | tr -d -}alertwithlesscronspam() {    msg=$1    if [ ! -f $LAST_ALERT ]; then        # party like it's        touch -t 199912312359 -- $LAST_ALERT    fi    # KLUGE this stat call is unportable, but that's shell for you    last_mtime=`stat -c '%Y' -- $LAST_ALERT`    last_abs_delta=`absmtimedelta $last_mtime`    if [ $last_abs_delta -gt $LAST_ALERT_THRESHOLD ]; then        # or here instead send smoke signals, carrier pigeon, whatever        echo $msg        touch -- $LAST_ALERT        exit 1    fi}if [ ! -r $MONITOR ]; then    alertwithlesscronspam no file alert for '$MONITOR'fiMONITOR_MTIME=`stat -c '%Y' -- $MONITOR`ABS_DELTA=`absmtimedelta $MONITOR_MTIME`if [ $ABS_DELTA -gt $THRESHOLD ]; then    alertwithlesscronspam mtime alert for '$MONITOR': $ABS_DELTA > $THRESHOLDfiPerhaps instead consider a standard monitoring framework, which may have support for file modification time checks or a plugin to do so, customizable alerting, metrics, better code than the above, etc.