Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # set -x
- DB_HOST='localhost'
- DB_USER=''
- DB_PASS=''
- DB_NAME=''
- EXCLUDES='Tables_in' # You can add tables which you don't want to be backed up
- BACKUP_DIR='/autobackups/backups'
- DELAY="1" # In seconds...
- full_backup_file="${BACKUP_DIR}/${DB_NAME}-all-$(date +%FT%T).tar"
- RESTORE=''
- RESTORE_FILE='/autobackups/backups/rb_common-all-2017-06-07T04:36:41.tar'
- function main
- {
- getoptions $*
- CREDENTIALS="-h ${DB_HOST} -u ${DB_USER} -p${DB_PASS} ${DB_NAME}"
- [ -z "${RESTORE}" ] && backup_tables || restore_backup
- }
- function backup_tables
- {
- mysql ${CREDENTIALS} -e 'SHOW TABLES' |
- egrep -v "${EXCLUDES}" |
- while read table
- do
- dump_file="${BACKUP_DIR}/${DB_NAME}-${table}-$(date +%FT%T).dump.sql.gz"
- dump_file="${dump_file//:/-}"
- echo "Backing up the table ${table} to the file ${dump_file} ..."
- [ ! -e "${BACKUP_DIR}" ] && { echo "Backup directory does not exist, creating..."; mkdir -p ${BACKUP_DIR}; }
- mysqldump ${CREDENTIALS} ${table} | gzip -9 > ${dump_file}
- [ -e "${full_backup_file}" ] &&
- tar uvf ${full_backup_file} ${dump_file} >&/dev/null ||
- tar cvf ${full_backup_file} ${dump_file} >&/dev/null
- rm -f ${dump_file}
- sleep ${DELAY}
- done
- }
- function restore_backup
- {
- [ ! -e "${RESTORE_FILE}" ] && { echo "You need to provide a valid RESTORE file with -f switch!"; exit 1; }
- mkdir -p /tmp/${DB_NAME}/
- tar xf ${RESTORE_FILE} -C /tmp/${DB_NAME}/
- ls /tmp/${DB_NAME}/${BACKUP_DIR} | while read tb
- do
- tb="${tb/\//}"
- tb=$(echo ${tb} | tr -d '\n')
- echo "Restoring the file ${tb} ..."
- zcat /tmp/${DB_NAME}/${BACKUP_DIR}/${tb} | mysql ${CREDENTIALS}
- sleep ${DELAY}
- done
- }
- function getoptions
- {
- while getopts "h:u:p:d:rf:" opt
- do
- case "${opt}" in
- h ) DB_HOST=${OPTARG};;
- u ) DB_USER=${OPTARG};;
- p ) DB_PASS=${OPTARG};;
- d ) DB_NAME=${OPTARG};;
- b ) BACKUP_DIR=${OPTARG};;
- r ) RESTORE='yes';;
- f ) RESTORE_FILE=${OPTARG};;
- esac
- done
- }
- main $*
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement