getRemoteBackup.sh 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/bin/bash
  2. #Read the backup folders and configuration variables from the config script
  3. . $1
  4. #Local variables
  5. globalErrors=0
  6. logFilePath="${logPath}${logFileName}"
  7. touch $tmpLogFilePath
  8. touch $logFilePath
  9. echo $logFilePath
  10. #Terminate if the last backup has not finished yet
  11. if pidof -o %PPID -x "$0" > /dev/null; then
  12. echo "Backup job already running. Exiting..."
  13. exit
  14. fi
  15. #Run the backup jobs as defined in the backup_folders array from the config
  16. echo "Starting backup job(s)" | tee $tmpLogFilePath
  17. for sourceFolder in "${!backup_folders[@]}"
  18. do
  19. #Exclude files
  20. IFS=';' read -ra split <<< "${backup_folders[$sourceFolder]}"
  21. #check if exclude file is given and file exists. Set to zero if not existing.
  22. if [[ -n ${split[1]} ]] && ! [ -f ${split[1]} ]; then
  23. echo "Error: Could not find exclude file ${split[1]}. Ignoring it." | tee -a $tmpLogFilePath
  24. split[1]=""
  25. fi
  26. destinationFolder=${split[0]}
  27. mkdir -p ${destinationFolder}
  28. while [ "$retryAttempts" -ge "0" ]
  29. do
  30. echo "Starting Job" | tee -a $tmpLogFilePath
  31. echo "SRC: ${sourceFolder}" | tee -a $tmpLogFilePath
  32. echo "DEST: ${destinationFolder}" | tee -a $tmpLogFilePath
  33. echo "Exclude file: ${split[1]}" | tee -a $tmpLogFilePath
  34. date | tee -a $tmpLogFilePath
  35. #SSH Host settings need to be set in the ssh client config!
  36. excludeDIRs=${split[1]}
  37. rsync --delete --out-format="%t %f %''b" -avz ${excludeDIRs:+"--exclude-from=$excludeDIRs"} ${sourceFolder} ${destinationFolder} | tee -a $tmpLogFilePath 2>&1
  38. rsyncExitCode=$?
  39. echo "Ending backup job" | tee -a $tmpLogFilePath
  40. date | tee -a $tmpLogFilePath
  41. echo "" | tee -a $tmpLogFilePath
  42. if [ $rsyncExitCode -eq 0 ]; then
  43. break
  44. else
  45. echo "Error: rsync exited with code $rsyncExitCode. Retrying..." | tee -a $tmpLogFilePath
  46. retryAttempts=$((retryAttempts-1))
  47. globalErrors=$((globalErrors+1))
  48. fi
  49. done
  50. done
  51. #copy over and delete older logs
  52. cat $tmpLogFilePath > $logFilePath
  53. find $logPath -type f -mtime +$rotationDays -name '*.log' -execdir rm -- '{}' \;
  54. #Mail Notifications
  55. if [ $globalErrors -eq 0 ]; then
  56. #send mail for success
  57. echo -e "To:$mailTo\nFrom:$mailFrom\nSubject:Backup SUCCESSFUL on $(date +'%c')\n\n$(cat $tmpLogFilePath)" | sendmail $mailTo
  58. else
  59. #send mail for failure
  60. echo -e "To:$mailTo\nFrom:$mailFrom\nSubject:Backup FAILED on $(date +'%c')\n\n$(cat $tmpLogFilePath)" | sendmail $mailTo
  61. fi
  62. #delete tmp file
  63. rm $tmpLogFilePath