Create local MySQL backups
Go to file
Yavuz Aydın 4c576d74e3 Show error message if mysql client is not found 2021-10-01 09:19:55 +02:00
README.md Added MySQL host, username and password and changed default retention to 1 day 2020-02-27 15:02:49 +01:00
backup_mysql.sh Show error message if mysql client is not found 2021-10-01 09:19:55 +02:00

README.md

Snel.com

MySQL / MariaDB backup script

Allows you to create and restore local MySQL / MariaDB backups.

Requirements

Method 1: Enter username and password in configuration section and uncomment.

Example:

...
# MySQL administrative user, uncomment if you want to use this instead of
# the value in /root/.my.cnf
MYSQL_USER='root'
# MySQL administrative user password, uncomment if you want to use this instead of
# the value in /root/.my.cnf
MYSQL_PW='ThisIsMyMySQLRootPassword'
...

Method 2: Requires a /root/.my.cnf file which contains credentials so the user root can login to the MySQL / MariaDB server with sufficient privileges without entering a password. Example /root/.my.cnf contents:

[client]
user=root
password=mysecretpassword

Don't forget to change the permissions:

sudo chmod 600 /root/.my.cnf

Test if it works with:

sudo mysqladmin status >> /dev/null 2>&1
if [ $? -ne 0 ]; then
  clear && echo 'Error: Unable to connect to MySQL Server!'
else
  clear && echo 'Successfully connected to the MySQL server!'
fi

Install script

sudo wget -O /usr/local/sbin/backup_mysql.sh https://git.snel.com/snelcom/backup-mysql/raw/branch/master/backup_mysql.sh
sudo chmod 700 /usr/local/sbin/backup_mysql.sh

Install cronjob

This will add a cronjob to root which will run this script daily at 0:10 am. Adjust as necessary.

(sudo crontab -l 2>/dev/null; sudo echo '10 0 * * * test -x /usr/local/sbin/backup_mysql.sh && /usr/local/sbin/backup_mysql.sh') | sudo crontab -

Recover database

Assuming you want to restore mytestdb from your backups made on 20190121-1540:

DB='mytestdb'
BACKUPDIR='/var/backup/mysql/20190121-1540'
sudo mysqldump ${DB} > /root/${DB}-$(date +%Y%m%d).sql
sudo mysql -e "DROP DATABASE ${DB}"
sudo mysql -e "CREATE DATABASE ${DB}"
for table in ${BACKUPDIR}/${DB}/*; do gunzip -c $table | sudo mysql ${DB}; done