1#!/bin/bash
2
3################################################################
4##
5## MySQL Database Backup Script
6## Written By: Rahul Kumar
7## URL: https://tecadmin.net/bash-script-mysql-database-backup/
8## Last Update: Jan 05, 2019
9##
10################################################################
11
12export PATH=/bin:/usr/bin:/usr/local/bin
13TODAY=`date +"%d%b%Y"`
14
15################################################################
16################## Update below values ########################
17
18DB_BACKUP_PATH='/backup/dbbackup'
19MYSQL_HOST='localhost'
20MYSQL_PORT='3306'
21MYSQL_USER='root'
22MYSQL_PASSWORD='mysecret'
23DATABASE_NAME='mydb'
24BACKUP_RETAIN_DAYS=30 ## Number of days to keep local backup copy
25
26#################################################################
27
28mkdir -p ${DB_BACKUP_PATH}/${TODAY}
29echo "Backup started for database - ${DATABASE_NAME}"
30
31
32mysqldump -h ${MYSQL_HOST} \
33 -P ${MYSQL_PORT} \
34 -u ${MYSQL_USER} \
35 -p${MYSQL_PASSWORD} \
36 ${DATABASE_NAME} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DATABASE_NAME}-${TODAY}.sql.gz
37
38if [ $? -eq 0 ]; then
39 echo "Database backup successfully completed"
40else
41 echo "Error found during backup"
42 exit 1
43fi
44
45
46##### Remove backups older than {BACKUP_RETAIN_DAYS} days #####
47
48DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`
49
50if [ ! -z ${DB_BACKUP_PATH} ]; then
51 cd ${DB_BACKUP_PATH}
52 if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
53 rm -rf ${DBDELDATE}
54 fi
55fi
56
57### End of script ####
58