Monday, March 7, 2016

Shell Script to monitor folder and send email with new files created on the folder

#!/bin/bash

# The following script is developed to monitor the folders and send an email with new files generated in the folders

a_dir=/u01/app/a_folder/
b_dir=/u01/app/b_folder/
c_dir=/u01/app/c_folder/

bfiles=$(find "$a_dir" -maxdepth 1 | sort)
mfiles=$(find "$b_dir" -maxdepth 1 | sort)
dfiles=$(find "$c_dir" -maxdepth 1| sort)

# Email Distribution lists for each Folder

A_DL="tri-1@email.com,tri-2@email.com,tri-3@email.com.com"
B_DL="tri-1@email.com,tri-2@email.com,tri-3@email.com.com"
C_DL="tri-1@email.com,tri-2@email.com,tri-3@email.com.com"


files=$(find "$a_dir" -maxdepth 1 | sort||find "$b_dir" -maxdepth 1 | sort||find "$c_dir" -maxdepth 1| sort)
IFS=$'\n'

while true
do
  sleep 5s

  anewfiles=$(find "$a_dir" -maxdepth 1 | sort)
  aadded=$(comm -13 <(echo "$afiles") <(echo "$anewfiles"))
  bnewfiles=$(find "$b_dir" -maxdepth 1 | sort)
  badded=$(comm -13 <(echo "$bfiles") <(echo "$bnewfiles"))
  cnewfiles=$(find "$c_dir" -maxdepth 1 | sort)
  cadded=$(comm -13 <(echo "$cfiles") <(echo "$cnewfiles"))
  [ "$aadded" != "" ] &&
    find $aadded -maxdepth 1 -printf '%Tc\t%s\t%p\n' | mail -s "File Generated in a_dir" -a $aadded "$A_DL"
   bfiles=$bnewfiles
  [ "$badded" != "" ] &&
    find $badded -maxdepth 1 -printf '%Tc\t%s\t%p\n' | mail -s "File Generated b_dir" -a $badded "$B_DL"
   bfiles=$bnewfiles
  [ "$cadded" != "" ] &&
    find $cadded -maxdepth 1 -printf '%Tc\t%s\t%p\n' | mail -s "File Generated c_dir" -a $cadded "$C_DL"
   cfiles=$cnewfiles

  files=$anewfiles
done

No comments:

Post a Comment