We use crontab and mysqldump to automatically backup mysql database
-
The simple way (only backup without crontab and manually)
$ mysqldump -u mysql_user -pmysql_password your_database > your_back_up_path/your_database.sql -
A little complex (well identified name)
$ mysqldump -u mysql_user -pmysql_password your_database > your_back_up_path/”(date +”%H:%M-%d-%m-%Y”)”.sql -
Add crontab
Store mysqldump command to a file
$ vim /root/backup.sh
add: mysqldump -u mysql_user -pmysql_password your_database > /your_back_up_path/”(date +”%H:%M-%d-%m-%Y”)”.sql
save and exit
$ chmod 777 /root/backup.sh
$ chmod 777 /your_back_up_path
now we set crontab
$ crontab -e
add:
30 12 * /root/backup.sh
30 23 * /root/backup.sh
save and exit
This means auto Automatic execution of the script at 12:30 and 23:30 each day
4.More complex (crontab and store it five days and then delete it)
next is content of /root/backup.sh, you need to modify db_user, db_passwd, backup_dir, and db.
!/bin/sh
backup.sh: backup mysql databases and keep newest 5 days backup.
db_user is mysql username
db_passwd is mysql password
db_host is mysql host
—————————–
db_user=”root”
db_passwd=”231212″
db_host=”localhost”
db=”cloud”
the directory for story your backup file.
backup_dir=”/var/backup”
date format for backup file (dd-mm-yyyy)
time=”$(date +”%H:%M-%d-%m-%Y”)”
mysql, mysqldump and some other bin’s path
MYSQL=”/usr/bin/mysql”
MYSQLDUMP=”/usr/bin/mysqldump”
MKDIR=”/bin/mkdir”
RM=”/bin/rm”
MV=”/bin/mv”
GZIP=”/bin/gzip”
check the directory for store backup is writeable
test ! -w $backup_dir && echo “Error: $backup_dir is un-writeable.” && exit 0
the directory for story the newest backup
test ! -d “$backup_dir/backup.0/” && $MKDIR “$backup_dir/backup.0/”
get all databases
all_db=”$($MYSQL -u $db_user -h $db_host -p$db_passwd -Bse ‘show databases’)”
for db in $all_db
do
$MYSQLDUMP -u $db_user -h $db_host -p$db_passwd $db | $GZIP -9 > “$backup_dir/backup.0/$time.$db.gz”
done
delete the oldest backup
test -d “$backup_dir/backup.10/” && $RM -rf “$backup_dir/backup.10”
rotate backup directory
for int in 9 8 7 6 5 4 3 2 1 0
do
if(test -d “$backup_dir”/backup.”$int”)
then
next_int=expr $int + 1
$MV “$backup_dir”/backup.”$int” “$backup_dir”/backup.”$next_int”
fi
done
exit 0;
save and exit
now we set crontab
$ crontab -e
add:
30 12 * /root/backup.sh
30 23 * /root/backup.sh
save and exit
This means auto Automatic execution of the script at 12:30 and 23:30 each day
Don’t forget chmod 777 /root/backup.sh and your backup file path