概述
每天定時遠程或者本地備份mysql數據庫,並且保存最新7天的備份內容。
腳本內容
[root@myhost ~]# cat /home/script/mysqlbackup.sh
#!/bin/sh
#define variables
#the login information of your mysql db.
login_user=""
login_passwd=""
db_host=""
db_port=""
#the real databases which you want to backup.
db_name0=""
#the dir for saving your backup file.
backup_dir="/home/backup/mysql_bak/$db_host_dir/"
#date format for the backup file (yyyy-mm-dd)
time=`date +"%Y-%m-%d"`
#the mysql,mysqldump and other bin's path
MYSQL_COMMDAND=""
MYSQLDUMP_COMMAND=""
MKDIR_COMMAND="/bin/mkdir"
RM_COMMAND="/bin/rm"
MV_COMMAND="/bin/mv"
GZIP_COMMAND="/bin/gzip"
# check the dir for saving backup file is writeable or not.
if [ ! -w $backup_dir ];then
echo "Error: $backup_dir is un-writeable." && exit 0
fi
#check if the dir for saving the backup file exists or not.
if [ ! -d ${backup_dir}/backup.0 ];then
$MKDIR_COMMAND -p "$backup_dir/backup.0"
fi
#starting to backup.
$MYSQLDUMP_COMMAND -P $db_port -u $login_user -h $db_host -p$login_passwd $db_name0 | $GZIP_COMMAND -9 > "$backup_dir/backup.0/$time.$db_name0.gz"
# delete the oldest backup
if [ -d "$backup_dir/backup.7" ];then
$RM_COMMAND -rf "$backup_dir/backup.7"
fi
# rotate backup directory
#for int in 6 5 4 3 2 1 0
for int in {6..0}
do
if [ -d "$backup_dir"/backup."$int" ];then
next_int=`expr $int + 1`
$MV_COMMAND "$backup_dir"/backup."$int" "$backup_dir"/backup."$next_int"
fi
done
exit 0;
定時任務
數據庫備份的定時任務儘量避開數據庫訪問的高峯期,可以選擇在半夜執行。
[root@myhost ~]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
30 3 * * * root /home/script/mysqlbackup.sh