Articles‎ > ‎Homemade Software‎ > ‎

Email if the file exists/disappears

This is just a script that I wrote to email me when a file shows up or when that same file disappears. I figure it might be handy to do the same thing somewhere else someday so you or I can just copy and paste as the need arises.

#!/bin/bash
startingdir="/home/yourhomedir"
cd $startingdir
thisfilenameflagfile="/tmp/$(basename $0).thisfilename_exists"
logfile="/tmp/$(basename $0).log"
echo -e "LOGFILE: $logfile\nthisfilename Flag File: $thisfilenameflagfile"
function rotatelog()
{
 touch $logfile
 #how old is the current log file? maybe it's time to start a new one. Are there any old ones to delete?
 if [ $(wc -l $logfile|awk '{print $1}') -gt 2000 ];then
  if [ -f "${logfile}.9.gz" ];then rm -v "${logfile}.9.gz";fi
  ct=9;while [ $ct -gt 1 ];do
   let ct--
   if [ -f "${logfile}.${ct}.gz" ];then
    mv -v "${logfile}.${ct}.gz" "${logfile}.$(( $ct + 1 )).gz"
   fi
  done
 fi
}
rotatelog

function sendemailthisfileremoved()
{
 echo "$(date) $0 - emailed pickup was done" | tee -a $logfile
cat <<EOF | /usr/sbin/sendmail -t
To: myemail@mydomain.com
Subject: Alert: File thisfilename removed
From: do-not-reply@mydomain.com


The file thisfilename has been removed.

Parent: $PPID $(ps -ocommand $PPID|grep -v 'COMMAND')

Email by: $0 at $(date) user:$(whoami) on $(hostname)
EOF
}
function sendemailthisfilenameready()
{
 echo "$(date) $0 - emailed file is ready for pickup" | tee -a $logfile
cat <<EOF | /usr/sbin/sendmail -t
To: myemail@mydomain.com
Subject: Alert: File thisfilename is present
From: do-not-reply@mydomain.com

The file thisfilename is present.

Parent: $PPID $(ps -ocommand $PPID|grep -v 'COMMAND')

Email by: $0 at $(date) user:$(whoami) on $(hostname)
EOF
}

if [ ! -f "thisfilename" ] && [ -f "$thisfilenameflagfile" ];then
 echo "File absent but flag exists, removing flag and emailing."
 sendemailthisfileremoved
 /bin/rm -vf "$thisfilenameflagfile"
else
 echo "File absent despite flag? Nope."
fi

if [ -f "thisfilename" ] && [ ! -f "$thisfilenameflagfile" ];then
 echo "File exists but flag absent, adding flag and emailing."
 touch "$thisfilenameflagfile"
 sendemailthisfilenameready
else
 echo "File exists but missing flag? Nope."
fi



Comments