Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

Automatic MySQL database backup

This simple script creates MySQL database backups and deletes the old ones. It's set to delete the backups older than 15 days but it could be set for more or less. In the comments of the code is also an exaple with hours instead of days as an exparation time. I use it as a cron service once a day but it could be used more or less often in case of need. NOTE: It could be a bad idea to use this script in some cases. So always consider the storage engine, database size, dump time and so on.
#!/bin/bash
# @author Samuil Banti - https://samiwell.eu
# @copyright (C) 2015 - Samuil Banti
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html

db_host="localhost"
db_name="my_database"
db_user="my_user"
db_pass="my_pass"

bkp_date=$(date +"%Y%m%d%H")
bkp_path="/home/my_user/database_bkp/auto_bkp/"

mysqldump -h$db_host -u$db_user -p$db_pass $db_name > $bkp_path$db_name"-"$bkp_date".sql"

#DELETE BKPS OLDER THAN 15 DayZ:
find $bkp_path*.sql -mtime +15 -exec rm -f {} \;

#DELETE BKPS OLDER THAN 3 HOURS:
#find $bkp_path*.sql -mmin +240 -exec rm -f {} \;

echo "$bkp_date - database backup done"
Download...