Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. #!/bin/bash
  2. # set -x
  3. DB_HOST='localhost'
  4. DB_USER=''
  5. DB_PASS=''
  6. DB_NAME=''
  7. EXCLUDES='Tables_in' # You can add tables which you don't want to be backed up
  8. BACKUP_DIR='/autobackups/backups'
  9. DELAY="1" # In seconds...
  10. full_backup_file="${BACKUP_DIR}/${DB_NAME}-all-$(date +%FT%T).tar"
  11. RESTORE=''
  12. RESTORE_FILE='/autobackups/backups/rb_common-all-2017-06-07T04:36:41.tar'
  13.  
  14.  
  15.  
  16.  
  17. function main
  18. {
  19. getoptions $*
  20. CREDENTIALS="-h ${DB_HOST} -u ${DB_USER} -p${DB_PASS} ${DB_NAME}"
  21. [ -z "${RESTORE}" ] && backup_tables || restore_backup
  22.  
  23. }
  24. function backup_tables
  25. {
  26. mysql ${CREDENTIALS} -e 'SHOW TABLES' |
  27. egrep -v "${EXCLUDES}" |
  28. while read table
  29. do
  30. dump_file="${BACKUP_DIR}/${DB_NAME}-${table}-$(date +%FT%T).dump.sql.gz"
  31. dump_file="${dump_file//:/-}"
  32. echo "Backing up the table ${table} to the file ${dump_file} ..."
  33. [ ! -e "${BACKUP_DIR}" ] && { echo "Backup directory does not exist, creating..."; mkdir -p ${BACKUP_DIR}; }
  34. mysqldump ${CREDENTIALS} ${table} | gzip -9 > ${dump_file}
  35. [ -e "${full_backup_file}" ] &&
  36. tar uvf ${full_backup_file} ${dump_file} >&/dev/null ||
  37. tar cvf ${full_backup_file} ${dump_file} >&/dev/null
  38. rm -f ${dump_file}
  39. sleep ${DELAY}
  40. done
  41. }
  42. function restore_backup
  43. {
  44. [ ! -e "${RESTORE_FILE}" ] && { echo "You need to provide a valid RESTORE file with -f switch!"; exit 1; }
  45. mkdir -p /tmp/${DB_NAME}/
  46. tar xf ${RESTORE_FILE} -C /tmp/${DB_NAME}/
  47. ls /tmp/${DB_NAME}/${BACKUP_DIR} | while read tb
  48. do
  49. tb="${tb/\//}"
  50. tb=$(echo ${tb} | tr -d '\n')
  51. echo "Restoring the file ${tb} ..."
  52. zcat /tmp/${DB_NAME}/${BACKUP_DIR}/${tb} | mysql ${CREDENTIALS}
  53. sleep ${DELAY}
  54. done
  55. }
  56. function getoptions
  57. {
  58. while getopts "h:u:p:d:rf:" opt
  59. do
  60. case "${opt}" in
  61. h ) DB_HOST=${OPTARG};;
  62. u ) DB_USER=${OPTARG};;
  63. p ) DB_PASS=${OPTARG};;
  64. d ) DB_NAME=${OPTARG};;
  65. b ) BACKUP_DIR=${OPTARG};;
  66. r ) RESTORE='yes';;
  67. f ) RESTORE_FILE=${OPTARG};;
  68. esac
  69. done
  70. }
  71. main $*
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement