Advertisement
opexxx

dirfdiffmail.sh

Jun 16th, 2014
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.92 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # 4/6/12 - Dan Woodruff www.makethenmakeinstall.com
  4. # This is a simple script to compare the current listing of a directory
  5. # with a previously known listing of the same directory.
  6. # If there is a change, it will mail the changes to a specified email address.
  7.  
  8. # validate the location selected is a directory
  9. [ -d "$1" ] || { echo "Usage: $0 directory"; exit 0; }
  10. fullpath=`readlink -f $1`
  11.  
  12. ##### Configuration options
  13. # email message recipients
  14. recipients="e@mail.com"
  15. # email message subject
  16. subject="Directory contents have changed. dirlistdiff for $fullpath"
  17. # directory to store db files, without trailing slash. default is the script's dir
  18. dbdir=$(dirname $(readlink -f $0))
  19. # command to run that creates and stores the database
  20. lscmd="ls"
  21. # to run the script without writing to stdout, as for a cron job, set to 1
  22. silent=1
  23. #####
  24.  
  25. # sanitize the directory name for use in the db file name
  26. cleaned_dir=$(echo "$1" | sed 's/\/$//' | sed 's/\//_/g')
  27. dbfile=$dbdir"/dirlistdiff-$cleaned_dir.txt"
  28.  
  29. # if the file doesn't yet exist, create one and exit
  30. if [ ! -f "$dbfile" ]; then
  31.     [ $silent -eq 0 ] && echo "First run, creating $dbfile."
  32.     $($lscmd $1 > $dbfile)
  33.     exit 0
  34. fi
  35.  
  36. # compare the current durectory listing with the contents of the database file
  37. new=$($lscmd $1 | diff --suppress-common-lines $dbfile - | grep ">" | sed 's/> //')
  38. removed=$($lscmd $1 | diff --suppress-common-lines $dbfile - | grep "<" | sed 's/< //')
  39.  
  40. mailstring=""
  41. # build the string of changes to mail
  42. if [ -n "$new" ]; then
  43.     mailstring="$mailstring""New items:\n"
  44.     mailstring="$mailstring$new\n\n"
  45. fi
  46. if [ -n "$removed" ]; then
  47.     mailstring="$mailstring""Removed items:\n"
  48.     mailstring="$mailstring$removed\n\n"
  49. fi
  50. # if anything changed, mail and update database
  51. if [ -n "$mailstring" ]; then
  52.     [ $silent -eq 0 ] && echo -e "$mailstring"
  53.     echo -e "$mailstring" | mail -s "$subject" "$recipients"
  54.     $($lscmd $1 > $dbfile)
  55. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement