Skip to content

Instantly share code, notes, and snippets.

@vivianspencer
Created January 9, 2024 16:34
Show Gist options
  • Save vivianspencer/0c0cda55e254fd028edf7bcf936903a4 to your computer and use it in GitHub Desktop.
Save vivianspencer/0c0cda55e254fd028edf7bcf936903a4 to your computer and use it in GitHub Desktop.
MariaDB automated backup script
#!/bin/bash
# Adapted from https://www.spacerex.co/how-to-automatically-backup-a-mysql-or-mariadb-server-with-mysqldump/
# Backup storage directory
backupfolder=/var/backups/db
logfile=/var/backups/db-bkp.log
# MySQL user
user=USER
password=PASSWORD
# Number of days to store the backup
keep_day=15
sqlfile=$backupfolder/all-database-$(date +%Y-%m-%d_%H-%M-%S).sql
zipfile=$backupfolder/all-database-$(date +%Y-%m-%d_%H-%M-%S).zip
echo Starting Backup [$(date +%Y-%m-%d_%H-%M-%S)] >> $logfile
# Create a backup
/usr/bin/mariadb-dump -u$user -p$password --all-databases >> $sqlfile
if [ $? == 0 ]; then
echo 'Sql dump created' >> $logfile
else
echo [error] mariadb-dump return non-zero code $? >> $logfile
exit
fi
# Compress backup
zip -j $zipfile $sqlfile
if [ $? == 0 ]; then
echo 'The backup was successfully compressed' >> $logfile
else
echo '[error] Error compressing backup' >> $logfile
exit
fi
rm $sqlfile
echo $zipfile >> $logfile
echo Backup complete [$(date +%Y-%m-%d_%H-%M-%S)] >> $logfile
# Delete old backups
find $backupfolder -mtime +$keep_day -delete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment